json
package jsonTask; import com.google.gson.Gson; import java.util.HashMap; public class Demo2Gson { public static void main(String[] args) { String jsonStr="{\"id\":\"1500100001\",\"name\":\"施笑槐\",\"age\":\"22\",\"gender\":\"女\",\"clazz\":\"文科六班\"}"; System.out.println(jsonStr); //Gson解析json字符串 Gson gson = new Gson(); //传入两个参数,一个字符串,一个解析的格式,用反射来写 HashMapmap = new HashMap (); HashMap hashMap = gson.fromJson(jsonStr, map.getClass()); System.out.println(hashMap); System.out.println(hashMap.get("id")); //将json解析成java对象 Student s = gson.fromJson(jsonStr, Student.class); System.out.println(s); //将java对象转化为json Student student = new Student("1222", "张三", 26, "男", "一班"); String s1 = gson.toJson(student); System.out.println(s1);
//输出结果
{"id":"1500100001","name":"施笑槐","age":"22","gender":"女","clazz":"文科六班"}
{gender=女, name=施笑槐, id=1500100001, clazz=文科六班, age=22}
1500100001
Student(id=1500100001, name=施笑槐, age=22, gender=女, clazz=文科六班)
{"id":"1222","name":"张三","age":26,"gender":"男","clazz":"一班"}
}
}
需要先导依赖
com.google.code.gson
gson
2.8.5
org.projectlombok
lombok
1.18.20
provided
public class Demo3 { public static void main(String[] args) { String jsonStr="{\"id\":\"1500100001\",\"name\":\"施笑槐\",\"age\":\"22\",\"gender\":\"女\",\"clazz\":\"文科六班\"}"; JSONObject jsonObject = JSON.parseObject(jsonStr); Object id = jsonObject.get("id"); System.out.println(id); Student student = JSON.parseObject(jsonStr, Student.class); int age = student.getAge(); System.out.println(age);
//输出结果
1500100001
22
}
}
原文:https://www.cnblogs.com/zyl777/p/15258270.html