转:
JSON
Gson
public class Demo_Gson {
public static void main(String[] args) {
//1、创建Gson对象
Gson g = new Gson();
//2、将对象转换为JSON字符串 String json = new Gson().toJSON(要转换的对象);
Book b = new Book("1002","金苹果","种苹果");
String json = g.toJson(b);
System.out.println(json);
//3、将JSON字符串转换为对象 对象 = new Gson().fromJson(JSON字符串,对象类型.class);
//Book b1 = g.fromJson(json,Book.class);
//转换为Book对象
Book b1 = g.fromJson("{"id":"1002","name":"金苹果","info":"种苹果"}",Book.class);
System.out.println(b1.getId());
//转换为Hashmap对象
HashMap data = g.fromJson("{"id":"1002","name":"金苹果","info":"种苹果"}",HashMap.class);
System.out.println(data.get("id"));
}
}
若JSON文件中有数组格式,转换为对象时,数组类型会变成ArrayList
public class Demo1 {
public static void main(String[] args) {
//1. 创建Gson对象
Gson g = new Gson();
//2. 将JSON字符串转换为对象 : {"id":"100","name":"金苹果","info":"种植苹果真辛苦","page":["锄禾日当午","汗滴禾下土","嘿嘿嘿嘿嘿"]}
HashMap data = g.fromJson("{"id":"100","name":"金苹果","info":"种植苹果真辛苦","page":["锄禾日当午","汗滴禾下土","嘿嘿嘿嘿嘿"]}", HashMap.class);
List page = (List) data.get("page");
System.out.println(data.get("page").getClass());
System.out.println(page.get(1));
}
}
FastJson
public class Demo_FastJson {
public static void main(String[] args) {
Book b = new Book("1002","金苹果","种苹果");
//将对象转换为JSON字符串 String json=JSON.toJSONString(要转换的对象);
String json = JSON.toJSONString(b);
System.out.println(json);
//将JSON字符串转换为对象
//类型 对象名=JSON.parseObject(JSON字符串, 类型.class)
Book b1 = JSON.parseObject("{"id":"1002","name":"金苹果","info":"种苹果"}",Book.class);
System.out.println(b1.getId());
//或List<类型> list=JSON.parseArray(JSON字符串,类型.class)
List<String> list = JSON.parseArray("["锄禾日当午","汗滴禾下土","嘿嘿嘿嘿嘿"]",String.class);
System.out.println(list.get(1));
}
}
转: