如何使用 json.net 将额外的属性添加到序列化的 JSON 字符串中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18692523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add an extra property into a serialized JSON string using json.net?
提问by peter
I am using Json.net in my MVC 4 program.
我在我的 MVC 4 程序中使用 Json.net。
I have an object itemof class Item.
我有一个itemclass对象Item。
I did:
string j = JsonConvert.SerializeObject(item);
我做了:
string j = JsonConvert.SerializeObject(item);
Now I want to add an extra property, like "feeClass" : "A"into j.
现在我想添加一个额外的属性,比如"feeClass" : "A"into j。
How can I use Json.net to achieve this?
我如何使用 Json.net 来实现这一点?
回答by Brian Rogers
You have a few options.
你有几个选择。
The easiest way, as @Manvik suggested, is simply to add another property to your class and set its value prior to serializing.
正如@Manvik 建议的那样,最简单的方法是向您的类添加另一个属性并在序列化之前设置其值。
If you don't want to do that, the next easiest way is to load your object into a JObject, append the new property value, then write out the JSON from there. Here is a simple example:
如果您不想这样做,下一个最简单的方法是将您的对象加载到 a 中JObject,附加新的属性值,然后从那里写出 JSON。这是一个简单的例子:
class Item
{
public int ID { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
Item item = new Item { ID = 1234, Name = "FooBar" };
JObject jo = JObject.FromObject(item);
jo.Add("feeClass", "A");
string json = jo.ToString();
Console.WriteLine(json);
}
}
Here is the output of the above:
这是上面的输出:
{
"ID": 1234,
"Name": "FooBar",
"feeClass": "A"
}
Another possibility is to create a custom JsonConverterfor your Itemclass and use that during serialization. A JsonConverterallows you to have complete control over what gets written during the serialization process for a particular class. You can add properties, suppress properties, or even write out a different structure if you want. For this particular situation, I think it is probably overkill, but it is another option.
另一种可能性是JsonConverter为您的Item类创建自定义并在序列化期间使用它。AJsonConverter允许您完全控制在特定类的序列化过程中写入的内容。如果需要,您可以添加属性、抑制属性,甚至写出不同的结构。对于这种特殊情况,我认为这可能有点矫枉过正,但这是另一种选择。
回答by roland
You could use ExpandoObject. Deserialize to that, add your property, and serialize back.
您可以使用 ExpandoObject。反序列化,添加您的属性,然后序列化回来。
Pseudocode:
伪代码:
Expando obj = JsonConvert.Deserializeobject<Expando>(jsonstring);
obj.AddeProp = "somevalue";
string addedPropString = JsonConvert.Serializeobject(obj);

