skip to Main Content

I have the following JSON string

{"fields": "{n  "CurrentPage": 14,n  "CurrentSubPageNo": 18,n  "IsFileUpload": false,n  "VisitedPages": [n    2,n    3,n    4,n    6,n    7,n    8,n    10,n    11,n    12,n    13,n    14n  ]n}"}

How can I make it to be like the following in C#?

{"fields":{"CurrentPage":14,"CurrentSubPageNo":18,"IsFileUpload":false,"VisitedPages":[2,3,4,6,7,8,10,11,12,13,14]}}

I am using Newtonsoft.Json and I do not know on how to achieve like the above result

Please do take a note that the value inside fields can be dynamic (which the key and value inside it can be present or not), which is why deserialize to a class for the value inside fields is not an option for me

Anyone knows on how to do it?

Thank you very much

2

Answers


  1. your "fields" property of json object is serialized twice, so you need just parse it twice. You can put all code in one line

    json = new JObject { ["fields"] = JObject.Parse(
     (string) JObject.Parse(json)["fields"])}.ToString(Newtonsoft.Json.Formatting.None);
    
    Login or Signup to reply.
  2. This is reasonably simple:

    • Deserialize to a JObject
    • Fetch the value of fields, which should be a string
    • Parse that as a JObject
    • Set the value of fields to the parsed value
    • Reserialize the JObject to a string

    Sample code – lacking error handling, of course:

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    
    string originalJson = File.ReadAllText("test.json");
    Console.WriteLine($"Original JSON: {originalJson}");
    
    JObject obj = JObject.Parse(originalJson);
    string fieldsJson = (string) obj["fields"];
    JObject fieldsObj = JObject.Parse(fieldsJson);
    obj["fields"] = fieldsObj;
    
    string newJson = obj.ToString(Formatting.None);
    Console.WriteLine($"New JSON: {newJson}");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search