如何使用json.net将额外的属性添加到序列化的JSON字符串中? [英] How to add an extra property into a serialized JSON string using json.net?
问题描述
我正在MVC 4程序中使用Json.net.
I am using Json.net in my MVC 4 program.
我有一个类Item
的对象item
.
我做到了:
string j = JsonConvert.SerializeObject(item);
现在,我想在j
中添加一个额外的属性,例如"feeClass" : "A"
.
Now I want to add an extra property, like "feeClass" : "A"
into j
.
我如何使用Json.net来实现这一目标?
How can I use Json.net to achieve this?
推荐答案
您有一些选择.
@Manvik建议,最简单的方法就是在类中添加另一个属性,并在序列化之前设置其值.
The easiest way, as @Manvik suggested, is simply to add another property to your class and set its value prior to serializing.
如果您不想这样做,下一个最简单的方法是将您的对象加载到JObject
中,附加新的属性值,然后从那里写出JSON.这是一个简单的示例:
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:
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);
}
}
以下是上面的输出:
{
"ID": 1234,
"Name": "FooBar",
"feeClass": "A"
}
另一种可能性是创建自定义 JsonConverter
作为您的Item
类,并在序列化过程中使用它. JsonConverter
允许您完全控制特定类在序列化过程中写入的内容.您可以根据需要添加属性,抑制属性,甚至写出不同的结构.对于这种特殊情况,我认为这可能是矫kill过正,但这是另一种选择.
Another possibility is to create a custom JsonConverter
for your Item
class and use that during serialization. A JsonConverter
allows 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.
这篇关于如何使用json.net将额外的属性添加到序列化的JSON字符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!