C#---第22:Newtonsoft中json/array的解析、创建、SelectToken(获取指定values)方法

1.解析json & array

(1)json解析

using Newtonsoft.Json.Linq;

string json = @"{CPU: 'Intel',
                Drives: [
                'DVD read/writer',
                '500 gigabyte hard drive']}";

JObject o = JObject.Parse(json);

Console.WriteLine(o.GetType());
Console.WriteLine(o.ToString());
Console.WriteLine(o["CPU"]);
Console.WriteLine(o["Drives"]);
Console.ReadKey();


Newtonsoft.Json.Linq.JObject

{
  "CPU": "Intel",
  "Drives": [
    "DVD read/writer",
    "500 gigabyte hard drive"
  ]
}

Intel

[
  "DVD read/writer",
  "500 gigabyte hard drive"
]



(2)array解析


using Newtonsoft.Json.Linq;

string json = @"['Small','Medium','Large']";
JArray a = JArray.Parse(json);

Console.WriteLine(a.GetType());
Console.WriteLine(a.ToString());
Console.WriteLine(a.Count());
Console.ReadKey();


Newtonsoft.Json.Linq.JArray

[
  "Small",
  "Medium",
  "Large"
]

3

(3)从文件中读取json

C#---第22:Newtonsoft中json/array的解析、创建、SelectToken(获取指定values)方法_第1张图片

#Progress.cs

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace Progress
{
    public class Progress
    {
        public static void Main()
        {
            var jo = OpenJsonFile();
            var driver = jo["Drives"][1];
            Console.WriteLine($"------->{driver}");
            Console.ReadKey();
        }

        public static JObject OpenJsonFile()
        {
            string fileName = @"C:\Users\XXX\repos\JsonStudyDeom\JsonFiles\FirstJsonFile.json";
            StreamReader file = File.OpenText(fileName);
            JsonTextReader reader = new JsonTextReader(file);
            JObject jsonObject = (JObject)JToken.ReadFrom(reader);
            return jsonObject;
        }

    }
}

# ------->500 gigabyte hard drive


# another demo for parse json file

using (StreamReader reader = File.OpenText(@"c:\person.json"))
{
    JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
    // do stuff
}


2.json/Aarray 的创建

(1) array 的创建


using Newtonsoft.Json.Linq;

namespace Progress
{
    public class Progress
    {
        public static void Main()
        {
            JArray array = new JArray();
            JValue text = new JValue("Manual text");
            JValue date = new JValue(new DateTime(2000, 5, 23));

            array.Add(text);
            array.Add(date);
            array.Add(123);
            array.Add("lastItem");

            Console.WriteLine(array.ToString());
            Console.WriteLine(array.Count());
            Console.WriteLine(array[1]);
            Console.ReadKey();
        }
    }
}


[
  "Manual text",
  "2000-05-23T00:00:00",
  123,
  "lastItem"
]

4

2000/5/23 0:00:00



(2) json 的创建


using Newtonsoft.Json.Linq;

namespace Progress
{
    public class Progress
    {
        public static void Main()
        {
            JObject o = JObject.FromObject(new
            {
                channel = new
                {
                    title = "James Newton-King",
                    link = "http://james.newtonking.com",
                    description = "James Newton-King's blog.",
                }
            });
            Console.WriteLine(o.ToString());
            Console.ReadKey();
        }
    }
}



{
  "channel": {
    "title": "James Newton-King",
    "link": "http://james.newtonking.com",
    "description": "James Newton-King's blog."
  }
}



3.SelectToken 获取json中指定的value/values

(1) SelectToken 获取json中对应的值


JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");


string name = (string)o.SelectToken("Manufacturers[0].Name");
// Acme Co

decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
// 50

string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
// Elbow Grease


(2) SelectToken with JsonPath


JObject o = JObject.Parse(@"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}");

// manufacturer with the name 'Acme Co'
JToken acme = o.SelectToken("$.Manufacturers[?(@.Name == 'Acme Co')]");

Console.WriteLine(acme);
// { "Name": "Acme Co", Products: [{ "Name": "Anvil", "Price": 50 }] }

// name of all products priced 50 and above
IEnumerable<JToken> pricyProducts = o.SelectTokens("$..Products[?(@.Price >= 50)].Name");

foreach (JToken item in pricyProducts)
{
    Console.WriteLine(item);
}
// Anvil
// Elbow Grease




# another demo

# 获取pins节点下,dataType=="Group"的字典,最终获取的字段为该字典中data.imageData.fill节点的value

$.pins.[?(@.dataType=='Group')].data.imageData.fill

C#---第22:Newtonsoft中json/array的解析、创建、SelectToken(获取指定values)方法_第2张图片


(3) SelectToken with LINQ


IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
// Lambton Quay
// Willis Street


IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
// null
// Headlight Fluid


decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
// 149.95


你可能感兴趣的:(C#基础,c#,json,Newtonsoft,SelectToken)