skip to Main Content

I am trying to return JsonObject as the interface of my method is –
public Task<ServiceResult<JsonObject>> GetTranslation(string language); but my test fails at expectedData:

  var apiResponse = new Dictionary<string, Dictionary<string, string>>() 
      {
        { "PAGE_NAME", new Dictionary<string, string>() { { "KEY_NAME", "LOCALE IN PARAMETER LANGUAGE" }, { "COPY_TO_CLIPBOARD", "Copy to clipboard" } } }
      };

      var jsonString = JsonConvert.SerializeObject(apiResponse);
      var expectedData = JsonConvert.DeserializeObject<JsonObject>(jsonString);

Error Message: Newtonsoft.Json.JsonSerializationException : Unable to find a default constructor to use for type System.Text.Json.Nodes.JsonObject. Path 'PAGE_NAME', line 1, position 13.

I can’t change the interface as it can’t deserialize the returned object.

2

Answers


  1. I would recommend two options,

    Option 1 :

    Create the Json object as class – you can convert using online Json to c# convertors or Paste your Json as C# using Edit>Paste Special>Paste JSON as C# (in Visual Studio), created below classes based on your sample provided.

    public class PAGENAME
    {
        public string KEY_NAME { get; set; }
        public string COPY_TO_CLIPBOARD { get; set; }
    }
    
    public class Root
    {
        public PAGENAME PAGE_NAME { get; set; }
    }
    

    Post that in the DeserializeObject , we should use Root class

    var apiResponse = new Dictionary<string, Dictionary<string, string>>()
      {
        { "PAGE_NAME", new Dictionary<string, string>() { { "KEY_NAME", "LOCALE IN PARAMETER LANGUAGE" }, { "COPY_TO_CLIPBOARD", "Copy to clipboard" } } }
      };
    
            var jsonString = JsonConvert.SerializeObject(apiResponse);
            var expectedData = JsonConvert.DeserializeObject<Root>(jsonString);
    

    Option 2:

    Use JObject from Newtonsoft.Json.Linq

    var expectedData = JsonConvert.DeserializeObject<JObject>(jsonString);
    

    The exact error is because JsonObject doesn’t have any default constructors.

    Login or Signup to reply.
  2. Try simply parsing the JSON string:

    using System.Text.Json.Nodes;
    
    // ...
    
    var expectedData = JsonObject.Parse(jsonString)!.AsObject();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search