JSON快速入门之GSON

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值