Search code examples
c#jsonjson.net

How do I convert an escaped JSON string within a JSON object?


I'm receiving a JSON object from a public API with a property that, itself, is an escaped JSON string.

{
   "responses":[
      {
         "info":"keep \"this\" in a string",
         "body":"{\"error\":{\"message\":\"Invalid command\",\"type\":\"Exception\",\"code\":123}}"
      },
      {
         "info":"more \"data\" to keep in a string",
         "body":"{\"error\":{\"message\":\"Other error\",\"type\":\"Exception\",\"code\":321}}"
      }
   ]
}

How do I convert this property into an actual JSON object (unescaped) in order to deserialize the entire response using NewtonSoft Json.NET?


Solution

  • Here's the workable solution I used based off of Sam I am's answer:

    dynamic obj = JsonConvert.DeserializeObject(json);
    foreach (var response in (IEnumerable<dynamic>)obj.responses)
    {
        response.body = JsonConvert.DeserializeObject((string)response.body);
    }
    string result = JsonConvert.SerializeObject(obj);