各种JSON格式数据
一、数组中有多个对象,对象中的字段是数组
[
{
"jingyesi": [
"床前明月光",
"疑是地上霜",
"举头望明月",
"低头思故乡"
]
},
{
"youziyin": [
"慈母手中线",
"游子身上衣",
"临行密密缝",
"意恐迟迟归",
"谁言寸草心",
"报得三春晖"
]
}
]
代码如下:
//1.声明数组
string[] arry1 = { "床前明月光", "疑是地上霜","举头望明月","低头思故乡"};
//2、声明对象
var obj1 = new JObject();
//3、把数组加入对象中的字段
obj1.Add("jingyesi",JArray.FromObject(arry1));
string[] arry2 = {"慈母手中线","游子身上衣","临行密密缝","意恐迟迟归","谁言寸草心","报得三春晖"};
var obj2 = new JObject();
obj2.Add("youziyin",JArray.FromObject(arry2));
//4.声明ogject的集合,把两个对象加入进去
List<object> data = new List<object>() { obj1,obj2};
Console.WriteLine(JArray.FromObject(data));
二、json数组中加入新项
1、数值型数组
JArray a = new JArray() {"1","2","3" };
a.Add("4");
Console.WriteLine(a);
输出:
[
"1",
"2",
"3",
"4"
]
如果要加入新的数值型数组
比如加入b数组
JArray b = new JArray() {"4","5","6" };
可以遍历b,把一项一项加入a
JArray a = new JArray() {"1","2","3" };
JArray b = new JArray() { "4", "5", "6" };
foreach (var s in b)
{
a.Add(s);
}
Console.WriteLine(a);
代码输出合并后的数组
[
"1",
"2",
"3",
"4",
"5",
"6"
]
2、对象型数组
string json = "[{\"Name\" : \"Jack\", \"Age\" : 34},{\"Name\" : \"Abel\",\"Age\":29}]";
var a = JArray.Parse(json);
var user = new
{
Name = "Lucy",
Age = 18
};
a.Add(JObject.FromObject(user));
Console.WriteLine(a);
输出:
[
{
"Name": "Jack",
"Age": 34
},
{
"Name": "Abel",
"Age": 29
},
{
"Name": "Lucy",
"Age": 18
}
]