JSON:

JavsScript Object Nottaion js对象简谱,是一种轻量级的数据交换格式

两种形式
1、对象表现–支持多层嵌套
注意:Java中,键也必须有引号,JavaScript中可以不需要

{
	"name":"小白",
	"age":15,
	 "child":[
	 	{
	 		"name":"小红",
	 		"age":20
		}
	 ]
}

2、数组形式
[“乔峰”,“段誉”…]

Java中JSON字符串使用

Java没有内置JSON转换的API,所以需要引入相关包来转换

Gson

使用Gson将独享转换为JSON字符串
	1、引入jar包
	2、在需要转换json字符串的位置编写如下代码
	String json =new Gson().toJSON(转换的对象)
JSON转对象
	类型 对象 =new Gson().fromJSon(JSON字符串,对象类型.class)

代码如下(示例):

public class Test{
	public static void main(String[] args) {
        Book book = new Book(1,251,"天龙八部","武侠");
        //对象转json
        String json = new Gson().toJson(book);
        System.out.println(json);
        //json转对象
        String jsonStr = "{\"id\":1,\"page\":251,\"name\":\"天龙八部\",\"type\":\"武侠\"}";
        Book book1 = new Gson().fromJson(jsonStr,Book.class);
        System.out.println(book1.getName());
        //{"id":1,"page":251,"name":"天龙八部","type":"武侠"}
        //json 转HashMap
        HashMap map = new Gson().fromJson(jsonStr,HashMap.class);
        System.out.println(map.get("page"));

        //{"id":1,"page":251,"name":"天龙八部","type":"武侠","ary":["段誉","乔峰","虚竹"]}
        //ary看上去是数组类型,实际上是ArrayList类型
        String jsonStr2= "{\"id\":1,\"page\":251,\"name\":\"天龙八部\",\"type\":\"武侠\",\"ary\":[\"段誉\",\"乔峰\",\"虚竹\"]}";
        HashMap map1 = new Gson().fromJson(jsonStr2,HashMap.class);
        System.out.println(map1.get("ary"));
        System.out.println(map1.get("ary").getClass());
    }
}
结果:
{"id":1,"page":251,"name":"天龙八部","type":"武侠"}
天龙八部
251.0
[段誉, 乔峰, 虚竹]
class java.util.ArrayList

FastJson

1、引入jar包
2、2、在需要转换json字符的位置编写如下代码
String json = JSON.toJSONString(要转换的对象)

json转对象
类型  对象名 = JSON.parseObject(JSON字符串,类型.class)
或
List<类型> list = JSON.parseArray(JSON字符串,类型.class)

代码如下(示例):

pulic class Test{
	 public static void main(String[] args) {
        //对象转json
        Book book = new Book(2,300,"射雕英雄传","武侠");
        String json = JSON.toJSONString(book);
        System.out.println(json);

        //json转对象
        //{"id":2,"name":"射雕英雄传","page":300,"type":"武侠"}
        String jsonStr = "{\"id\":2,\"name\":\"射雕英雄传\",\"page\":300,\"type\":\"武侠\"}";
        Book book1 = JSON.parseObject(json,Book.class);
        System.out.println(book1.getName());

        //["郭靖","黄蓉","欧阳锋"]
        String listStr = "[\"郭靖\",\"黄蓉\",\"欧阳锋\"]";
        List<String> strings = JSON.parseArray(listStr,String.class);
        System.out.println(strings);
    }
}
结果:
{"id":2,"name":"射雕英雄传","page":300,"type":"武侠"}
射雕英雄传
[郭靖, 黄蓉, 欧阳锋]