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

我有一个Item班的item号物体.

I did: string j = JsonConvert.SerializeObject(item);

现在我想增加一个额外的属性,比如"feeClass" : "A"j.

如何使用Json.net来实现这一点?

推荐答案

你有几个 Select .

The easiest way, as @Manvik suggested, is simply to add another property to your class and set its value prior to serializing.

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);
    }
}

Here is the output of the above:

{
  "ID": 1234,
  "Name": "FooBar",
  "feeClass": "A"
}

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相关问答推荐

SWIFT中的网络经理

使用JQ在数组中 Select 第一个具有匹配项的项

数据到jsonObject到数据到 struct 是可能的吗?

用 Jolt 替换 JSON 中的值

Jolt Spec 跳过数组中的第一个元素

取消嵌套数组并将数组名称添加为附加字段

jq :当路径可变时更新 json 内容

如何使用 serde_json 构建有状态的流式解析器?

使用杰克逊解析Kotlin 中的通用密封类

使用 KQL 和外部 data() 运算符从 json 文件中提取信息

使用 SwiftUI 在 API 调用中解码嵌套 JSON 响应时遇到问题

我无法在 Go - Gin 中解析日期/时间

Powershell 无法从名为 count 的键中获取价值

在循环中将变量添加到 bash 数组

如何使用 gson 将数据保存在 json 文件中?

jQuery JSON 响应总是触发 ParseError

使用 Retrofit 解析动态密钥 Json 字符串

ASP.NET Core API 仅返回列表的第一个结果

获取一个数字的 PHP 对象属性

有没有一种快速的方法可以在文本编辑器中将 JavaScript 对象转换为有效的 JSON?