Search code examples
c#asp.net-corejson.netasp.net-core-webapijson-serialization

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:

{
    "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,
        });