JSON学习笔记

项目中用到了json,此处就简单介绍其用法。

认识JSON: 

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、C#Java、JavaScript、PerlPython等)。这些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。(百度百科).

JSON是JavaScript对象表示法,它是一种基于文本,独立于语言的轻量级数据交换格式。XML也是一种数据交换格式,为什么没有选择XML呢?因为XML虽然可以作为跨平台的数据交换格式,但是在JS(JavaScript的简写)中处理XML非常不方便,同时XML标记比数据多,增加了交换产生的流量,而JSON没有附加的任何标记,在JS中可作为对象处理,所以我们更倾向于选择JSON来交换数据。

JSON结构:

json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构。
1、对象:对象在js中表示为“{}”括起来的内容,数据结构为 {key:value,key:value,...}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是 数字、字符串、数组、对象几种。
var jsonObj = { "name": "tom", "age": 12 }
2、数组:数组在js中是中括号“[]”括起来的内容,数据结构为 ["java","javascript","vb",...],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。
var jsonArr = [
            { "id": 1, "name": "john" },
            {"age":13,"address":"str1"}
        ]
经过对象、数组2种结构就可以组合成复杂的数据结构了。
 
JS中使用json:
var str = jsonObj.name;//tom
        var str2 = jsonArr[0].id;//1
        var str3 = jsonArr[1].age;//13

.net中使用json,常用的两种方法:

定义类:

//类:人
    public class Person
    {
        public int id { get; set; }
        public Student student { get; set; }
    }

    //类:学生
    public class Student
    {
        public int score { get; set; }
        public string grade { get; set; }
    }
View Code

1、引入using Newtonsoft.Json;处理json最常用的插件Newtonsoft.Json。

对象转换为json字符串:

Student student = new Student();
            student.grade = "二年级";
            student.score = 99;

            Person person = new Person();
            person.id = 5;
            person.student = student;

            string jsonstr = JsonConvert.SerializeObject(person);

结果:

{"id":5,"student":{"score":99,"grade":"二年级"}}

json字符串转换为对象:

可以使用JObject或JArray的Parse方法轻松地将json字符串转换为json对象,然后通过对象的方式提取数据。

JObject ob = JObject.Parse(jsonstr);
            int id = Convert.ToInt32(ob["id"].ToString());//5
            Student stu = (ob["student"]).ToObject<Student>();
            int score = stu.score;//99

2、使用.net框架自带类库,命名空间System.Web.Script.Serialization,添加引用:System.Web.Extensions.dll。

对象转换为json字符串:

System.Web.Script.Serialization.JavaScriptSerializer jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            System.Text.StringBuilder sb = new StringBuilder();
            jsonSerializer.Serialize(person, sb);
            string jsonstr = sb.ToString();

json字符串转换为对象:

Person ob = jsonSerializer.Deserialize<Person>(jsonstr);
            int id = ob.id;//5
            Student stu = ob.student;
            int score = stu.score;//99

后台处理特殊json字符串:

有时在后台接收到一个json字符串或者数组,可以根据得到的字符串进行类定义,然后解析得到比较理想的属性值。

因为经常用到,此处将web请求响应代码贴出来,方便查看。

string url = "http://192.168.5.111:8001";
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest) WebRequest.Create(url);
            request.ContentType = "application/json; charset=UTF-8";
            request.Method = "POST";
       string jsonstr = "";
byte[] data = System.Text.Encoding.UTF8.GetBytes(jsonstr); request.ContentLength = data.Length; System.IO.Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse) request.GetResponse(); System.IO.StreamReader streamReader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8); string text = streamReader.ReadToEnd(); streamReader.Close();

参考:

JSON详解

原文地址:https://www.cnblogs.com/ysyn/p/5433171.html