• 黄聪:C#如何操作JSON数据(读取、分析)


    使用开源的类库Newtonsoft.Json(下载地址http://json.codeplex.com/)。下载后加入工程就能用。通常可以使用JObject, JsonReader, JsonWriter处理。这种方式最通用,也最灵活,可以随时修改不爽的地方。


    (1)使用JsonReader读Json字符串:

    string jsonText = @"{""input"" : ""value"", ""output"" : ""result""}";
    JsonReader reader = new JsonTextReader(new StringReader(jsonText));
    
    while (reader.Read())
    {
        Console.WriteLine(reader.TokenType + "		" + reader.ValueType + "		" + reader.Value);
    }

    (2)使用JsonWriter写字符串:

    StringWriter sw = new StringWriter();
    JsonWriter writer = new JsonTextWriter(sw);
    
    writer.WriteStartObject();
    writer.WritePropertyName("input");
    writer.WriteValue("value");
    writer.WritePropertyName("output");
    writer.WriteValue("result");
    writer.WriteEndObject();
    writer.Flush();
    
    string jsonText = sw.GetStringBuilder().ToString();
    Console.WriteLine(jsonText);

     (3)使用JObject读写字符串:

    JObject jo = JObject.Parse(jsonText);
    string[] values = jo.Properties().Select(item => item.Value.ToString()).ToArray();

     (4)使用JsonSerializer读写对象(基于JsonWriter与JsonReader): 

    数组型数据

    复制代码
    string jsonArrayText1 = "[{'a':'a1','b':'b1'},{'a':'a2','b':'b2'}]";
    JArray ja = (JArray)JsonConvert.DeserializeObject(jsonArrayText1);
    string ja1a = ja[1]["a"].ToString();
    //或者
    JObject o = (JObject)ja[1];
    string oa = o["a"].ToString();
    复制代码

    嵌套格式

    string jsonText = "{"beijing":{"zone":"海淀","zone_en":"haidian"}}";
    JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);
    string zone = jo["beijing"]["zone"].ToString();
    string zone_en = jo["beijing"]["zone_en"].ToString();

    自定义类Project

    复制代码
    Project p = new Project() { Input = "stone", Output = "gold" };
    JsonSerializer serializer = new JsonSerializer();
    StringWriter sw = new StringWriter();
    serializer.Serialize(new JsonTextWriter(sw), p);
    Console.WriteLine(sw.GetStringBuilder().ToString());

    StringReader sr = new StringReader(@"{""Input"":""stone"", ""Output"":""gold""}");
    Project p1 = (Project)serializer.Deserialize(new JsonTextReader(sr), typeof(Project));
    Console.WriteLine(p1.Input + "=>" + p1.Output);
    复制代码

      上面的代码都是基于下面这个Project类定义:

    class Project
    {
        public string Input { get; set; }
        public string Output { get; set; }
    }

      此外,如果上面的JsonTextReader等类编译不过的话,说明是我们自己修改过的类,换成你们自己的相关类就可以了,不影响使用。

  • 相关阅读:
    例题6-8 Tree Uva548
    例题6-7 Trees on the level ,Uva122
    caffe Mac 安装
    Codeforces Round #467 (Div. 1) B. Sleepy Game
    Educational Codeforces Round37 E
    Educational Codeforces Round 36 (Rated for Div. 2) E. Physical Education Lessons
    Good Bye 2017 E. New Year and Entity Enumeration
    Good Bye 2017 D. New Year and Arbitrary Arrangement
    Codeforces Round #454 D. Seating of Students
    浙大紫金港两日游
  • 原文地址:https://www.cnblogs.com/huangcong/p/4381451.html
Copyright © 2020-2023  润新知