PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 25, 2022

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

 July 25, 2022     c#, json, json.net     No comments   

Issue

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);


Answered By - Kcoder
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing