通过JObject和JArray创建JSON对象
我们先用非常简单的方法来动态创建一些JSON,可通过JToken派生的JSON.NET对象来进行,最常见的JToken派生的类是JObject和JArray。
正是因为JToken实现了IDynamicMetaProvider动态语言接口,所以可以使用dynamic关键字直观地创建动态对象,并把这个动态对象序列化为JSON字符串。 我们通过JArray和JObject来创建一个示例:
[TestMethod]
public void JObjectOutputTest()
{
// strong type instance
var jsonObject = new JObject();
// you can explicitly add values here
jsonObject.Add(“Entered”, DateTime.Now);
// dynamic expando instance you can add properties to
dynamic album = jsonObject;
album.AlbumName = “Dirty Deeds Done Dirt Cheap”;
album.Artist = “AC/DC”;
album.YearReleased = 1976;
album.Songs = new JArray() as dynamic;
dynamic song = new JObject();
song.SongName = “Dirty Deeds Done Dirt Cheap”;
song.SongLength = “4:11”;
album.Songs.Add(song);
song = new JObject();
song.SongName = “Love at First Feel”;
song.SongLength = “3:10”;
album.Songs.Add(song);
Console.WriteLine(album.ToString());
}
运行上面的示例代码,就能形成以下结构的JSON内容:
{
“Entered”: “2012-08-18T13:26:37.7137482-10:00”,
“AlbumName”: “Dirty Deeds Done Dirt Cheap”,
“Artist”: “AC/DC”,
“YearReleased”: 1976,
“Songs”: [
{
“SongName”: “Dirty Deeds Done Dirt Cheap”,
“SongLength”: “4:11”
},
{
“SongName”: “Love at First Feel”,
“SongLength”: “3:10”
}
]
}
C#给JSON对象添加一个键值对
/// 添加一个属性
///
///
/// 待添加属性的对象
/// 键名
/// 值
/// 添加属性后的对象
public static object Add(object obj, string key, object value)
{
JObject jObj = JObject.Parse(JsonConvert.SerializeObject(obj));
jObj.Add(new JProperty(key, value));
return JsonConvert.DeserializeObject(jObj.ToString());
}
————————————————
版权声明:本文为CSDN博主「BruceYang~」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_34187499/article/details/99085935