如何使用 json.net 将额外的属性添加到序列化的 JSON 字符串中? [英] How to add an extra property into a serialized JSON string using json.net?

查看:31
本文介绍了如何使用 json.net 将额外的属性添加到序列化的 JSON 字符串中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 MVC 4 程序中使用 Json.net.

I am using Json.net in my MVC 4 program.

我有一个 Item 类的对象 item.

I have an object item of class Item.

我做到了:字符串 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 允许您完全控制在特定类的序列化过程中写入的内容.如果需要,您可以添加属性、抑制属性,甚至可以写出不同的结构.对于这种特殊情况,我认为这可能是矫枉过正,但这是另一种选择.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆