<dependencies>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
</dependencies>
首先通过maven下载两个jar包,fastjson和gson
json的格式:
- JSON 对象被花括号 {} 包围。
- JSON 对象以键/值对书写。
- 键必须是字符串,值必须是有效的 JSON 数据类型(字符串、数字、对象、数组、布尔或 null)。
- 键和值由冒号分隔。
- 每个键/值对由逗号分隔。
gson
json字符串为"studentid":001,“name”:“zhang”,“score”:98,“hobby”:“代码”,“clazz”:“一班”
- json转为指定对象类型
gson.fromJson(jsonstr, 类名.class)
这样相当于是将json里面的值传入对应的对象的变量中 - 对象转换为json对象
gson.toJson(对象)
package Demo;
import com.google.gson.Gson;
import java.util.HashMap;
public class jsonDemo {
public static void main(String[] args) {
String jsonstr="{\"studentid\":001,\"name\":\"zhang\",\"score\":98,\"hobby\":\"敲代码\",\"clazz\":\"一班\"}";
System.out.println(jsonstr);
Gson gson = new Gson();
//json转化为对象
//转化为hashmap对象
HashMap hashMap = gson.fromJson(jsonstr, HashMap.class);
System.out.println(hashMap);
//转化为Student类对象
//注意Student类里面的变量个数与名字要和json里面相对应
//比如我将Student里的hobby成员变量改为gender,结果就会变成
//Student{studentid=1, name='zhang', score=98, gender='null', clazz='一班'}
System.out.println("----------------");
Student stu = gson.fromJson(jsonstr, Student.class);
System.out.println(stu.toString());
//通过student类里面的方法,获取单个属性值
System.out.println(stu.getHobby());
System.out.println("----------------");
//对象转化为json
String s = gson.toJson(stu);
System.out.println(s);
//对象应该是key——value格式,如果不是则无法转换,但是不会报错,会原样输出
String[] strings = {"a","b","c","d","e"};
String s1 = gson.toJson(strings);
System.out.println(s1);
}
}
fastjson
- 将json对象转换为指定对象
JSON.parseObject(jsonstr, 类名.class) - 将json对象转换为JSONObject对象(可以直接获取value值,不用创建新的对象)
JSON.parseObject(jsonstr) - 将对象转换为json对象
JSON.toJSON(对象)
package Demo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class jsonDemo1 {
public static void main(String[] args) {
String jsonstr="{\"studentid\":001,\"name\":\"zhang\",\"score\":98,\"hobby\":\"敲代码\",\"clazz\":\"一班\"}";
//fastjson通过反射进行转换,将json转换为指定对象,这里是Student对象
Student student = JSON.parseObject(jsonstr, Student.class);
System.out.println(student.toString());
//如果只是想获取其中一个value值,那么像上面这样重新创建一个新的对象很麻烦
//使用JSON.parseObject方法时,可以不指定后面的类
//这样就会默认转换为JSONObject对象,而不用再创建Student类或者hashmap对象
//JSONObject对象里面存储的数据是key——value类型吗,可以通过get(key)的方式直接获取value值
JSONObject jsonObject = JSON.parseObject(jsonstr);
Object name = jsonObject.get("name");
System.out.println(name);
System.out.println("---------------");
//将对象转换为json
//Object类型的json
Object o = JSON.toJSON(student);
System.out.println(o);
//指定为String类型的json
String s = JSON.toJSONString(student);
System.out.println(s);
}
}