I am using Json.net in my MVC 4 program.
我有一个Item
班的item
号物体.
I did:
string j = JsonConvert.SerializeObject(item);
现在我想增加一个额外的属性,比如"feeClass" : "A"
到j
.
如何使用Json.net来实现这一点?
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.