首先來談談GSON相比於org.json的優點:
1.功能性更強,可以將JSON對象解析成JAVA對象,可以解析日期和集合類型數據。
2.更加人性化,可以在JSON解析的過程中改變一些東西。
3.可以使用註解。
GSON的使用:
1.先創建一個maven工程
2.用到的jar包:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.1</version>
</dependency>
3.創建JSON對象,和GSON的一些特性
Person person = new Person();
person.setName("王i下奧爾");
person.setAge(10);
person.setBirthday("1996/09/13");
person.setHas_girlfirend(false);
person.setMajor(new String[]{"af","as"});
person.setCar("sf");
person.setSchool("南翔");
person.setComment("這是一個註釋");
person.setSex("男");
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
//在json解析過程中可以進行一些操作
builder.setFieldNamingStrategy(new FieldNamingStrategy() {
@Override
public String translateName(Field field) {
if (field.getName().equals("car")) {
return "CAR";
}
return field.getName();
}
});
Gson gson = builder.create();
System.out.println(gson.toJson(person));
4.GSON解析JSON文件
File file = new File(ReadJsonSimple.class.getResource("wagnxiaoer.json").getFile());
String content = FileUtils.readFileToString(file);
Gson gson = new GsonBuilder().setDateFormat("yyyy/MM/dd").create();
PersonWithBirthday wangxiaoer = gson.fromJson(content, PersonWithBirthday.class);
System.out.println(wangxiaoer.getBirthday().toLocaleString());
System.out.println(wangxiaoer);
備註:可以看到GSON比之org.json而言功能更加強大,基本能滿足開發的需求。