使用JsonConvert以特定格式序列化对象

问题描述 投票:0回答:1

我正在使用 JsonConvert.SerializeObject 方法来序列化此对象:

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

我正在使用此代码:

  using System.Text.Json.Nodes;

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

但是我得到了这个结果:

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

但我需要这样:

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

我可以使用 JsonSerializerSettings,但我不知道我到底需要做什么

c# asp.net-core asp.net-core-webapi
1个回答
0
投票

您正在混合 JSON 序列化库。当您使用

Netwonsoft.Json
进行序列化时,JsonObject 来自 System.Text.Json 库。

要么在 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 
    });

参考:从Newtonsoft.Json迁移到System.Text.Json

或在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(objFromNewton, Formatting.None,
    new JsonSerializerSettings()
    {
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
    });
© www.soinside.com 2019 - 2024. All rights reserved.