C# Newtonsoft.Json之LINQ To Json实例(一)

时间:2022-09-16 05:16:27

一、LINQ to JSON 常用实例1:

JObject o = JObject.Parse(@"{
    'CPU': 'Intel',
    'Drives': [
    'DVD read/writer',
    '500 gigabyte hard drive'
    ]
    }");
string cpu = (string)o["CPU"];
Console.WriteLine(cpu);//CPU
string firstDrive = (string)o["Drives"][0];
Console.WriteLine(firstDrive);// DVD read/writer
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
foreach (var item in allDrives)
{
    Console.WriteLine(item); // DVD read/writer
                                //500 gigabyte hard drive
}

二、Parsing JSON 将json 字符串转换成对象

string json = @"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
],
'Mouses':{
'one':'小米',
'two':'戴尔'
}
}";
JObject computer = JObject.Parse(json);
Console.WriteLine(computer.First.ToString());//"CPU": "Intel"
Console.WriteLine(computer.Last.ToString()); //"Mouses": { "one": "小米","two": "戴尔"}
string one = computer["Mouses"]["one"].ToString(); //小米
Console.WriteLine(one);

//2.转化数组
string json2 = @"['张三','李四','王五']";
JArray array2 = JArray.Parse(json2);
Console.WriteLine(array2.Type);//Array
Console.WriteLine(array2[1]); //李四

string json3 = @"[{name:'张三'},{name:'李四'}]";
JArray array3 = JArray.Parse(json3);
Console.WriteLine(array3.Type);//Array
Console.WriteLine(array3[1]);//{ "name": "李四" }


//3.转化Json 文件
using (StreamReader sr = File.OpenText(@"F:\ABCSolution\JsonSolution\JsonSolution\Data\json1.json"))
{
    JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(sr));
    Console.WriteLine(o["CPU"]);//Intel
    //如果没有找到抛出异常
    //举例说明,只是获取 o["CPU"] 为空不会抛出异常,
    //o["CPU"]["one"] 如果o["CPU"] 为空就会抛出异常
    string result = (string)o["Mouses"]["one"]; //小米
    Console.WriteLine(result);
}

三、Creating JSON 将对象属性转换成json 字符串

// 动态生成json字符串
//1.创建数组
JArray array = new JArray();
array.Add(new JValue("张三"));
array.Add(new JValue("李四"));
string json1 = array.ToString();
Console.WriteLine(json1);
//[
//  "张三",
//  "李四"
//]

//2.创建对象
JObject obj = new JObject();
obj.Add("name",new JValue("张三"));
obj.Add("age",new JValue("20"));
string json2 = obj.ToString();
Console.WriteLine(json2);
//{
//"name": "张三",
//  "age": "20"
//}

//3.创建对象方式2,使用匿名对象
JObject obj2 = JObject.FromObject(new { name = "李四", Birthday = DateTime.Now });
string json3 = obj2.ToString();
Console.WriteLine(json3);
//{
//"name": "李四",
//  "Birthday": "2016-09-09T14:53:23.0307889+08:00"
//}

LINQ to JSON 实例二:http://blog.csdn.net/u011127019/article/details/52487130

Newtonsoft.Json 简介:http://blog.csdn.net/u011127019/article/details/51706619