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
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.
Post that in the DeserializeObject , we should use Root class
Option 2:
Use JObject from Newtonsoft.Json.Linq
The exact error is because JsonObject doesn’t have any default constructors.
Try simply parsing the JSON string: