Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot convert Dictionary<string, Dictionary<string, string>> to JsonObject in C#

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try simply parsing the JSON string:

using System.Text.Json.Nodes;

// ...

var expectedData = JsonObject.Parse(jsonString)!.AsObject();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading