JSON 是一种存储和交换数据的语法。
下面是一组JSON数据,我们来根据这组数据分析JSON是由什么组成?
{
"name":"潮田渚",
"age":"15",
"class":[
"3年E班",
{
"teacher":"杀老师",
"info":"一个行动速度达到20马赫同时拥有超强再生能力和超乎常人的智慧的未知章鱼型生物"
}
],
"info":{
"hair":"蓝色",
"gender":"男"
}
}
其实JSON数据很简单,分为对象格式和数组格式。对象是由一组大括号{}表示,数组是一组中括号[]表示。键与值之间使用冒号连接,多个键值对之间使用逗号分隔,键值对的键应使用引号引住 (通常Java解析时,键不使用引号会报错. 而JS能正确解析) 键值对的值,,可以是JS中的任意类型的数据。
知道了JSON数据是如何组成的,那我们要怎么获取到里面我们需要到的数据呢?有两种解析方式能够解析JSON数据。
1.Gson解析
Gson解析的步骤:
1.导入相应的jar包
2.创建Gson对象
3.转换要转换的对象如下代码即可:
//对象转换Json
String str = new Gson().toJson(new Student("张三",18));
System.out.println(str);
//Json转对象
Student s1= new Gson().fromJson("{\"name\":\"张三\",\"age\":18}", Student.class);
System.out.println(s1.getName());
//Json转集合
HashMap hashMap = new Gson().fromJson("{\"name\":\"张三\",\"age\":18}", HashMap.class);
System.out.println(hashMap);
控制台结果如下:
2.FastJson
FastJson解析的步骤:
1.导入相应的jar包
2.转换要转换的对象如下代码即可:
//对象转Json
String s = JSON.toJSONString(new Student("李四",20));
System.out.println(s);
//Json转对象
Student s1 = JSON.parseObject("{\"age\":20,\"name\":\"李四\"}",Student.class);
System.out.println(s1);
//Json转集合
List<String> str = JSON.parseArray("[\"一二三\",\"四五六\"]", String.class);
System.out.println(str);
控制台结果如下:
Gson的jar包下载地址
FastJson的jar包下载地址
希望能够帮助到你。