JSON快速入门之GSON

xiaoxiao2021-02-28  89

首先来谈谈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而言功能更加强大,基本能满足开发的需求。

转载请注明原文地址: https://www.6miu.com/read-70410.html

最新回复(0)