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

Serialize Object using JsonConvert with specific format

I am using JsonConvert.SerializeObject method to serialize this object:

var objx = new JsonObject
{
    ["prob1"] = new JsonObject
    {
        ["phone"] = "1019577756",
        ["name"] = "Jan",
        ["type"] = "Agent"
    }
};

I am using this code:

  using System.Text.Json.Nodes;

  var jsonString = JsonConvert.SerializeObject(objx, Formatting.None,
        new JsonSerializerSettings()
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        });

But I get this result:

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

{
    "prob1":
    {
         "phone":
         {
               "_value": "1019577756",
               "Value": "1019577756",
               "Options": null
         },
         "name": 
         {
               "_value": "Jan",
               "Value": "Jan",
               "Options": null
         },
         "type"
         {
               "_value": "Agent",
               "Value": "Agent",
               "Options": null
         }
   }
}

But I need like this:

{
   "prob1": 
   {
       "phone": "1019577756",
       "name": "Jan",
       "type": "Agent"
   }
}

Can I use JsonSerializerSettings, but I do not know what exactly I need to do

>Solution :

You are mixing the JSON serialization library. JsonObject is from the System.Text.Json library while you are serializing with Netwonsoft.Json.

Either fully implement in System.Text.Json:

using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;

var jsonString = JsonSerializer.Serialize(objx, 
    new JsonSerializerOptions 
    { 
        WriteIndented = false, 
        ReferenceHandler = ReferenceHandler.IgnoreCycles 
    });

Reference: Migrate from Newtonsoft.Json to System.Text.Json

Or fully implement in Newtonsoft.Json:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

var objx = new JObject
{
    ["prob1"] = new JObject
    {
        ["phone"] = "1019577756",
        ["name"] = "Jan",
        ["type"] = "Agent"
    }
};

var jsonString = JsonConvert.SerializeObject(objx, Formatting.None,
    new JsonSerializerSettings()
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
    });
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