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(); //传入两个参数,一个字符串,一个解析的格式,用反射来写 HashMap<String, String> map = new HashMap<String, String>(); 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":"一班"}
}
}
需要先导依赖
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
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://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>