JSON知识总结- Gson(四)List和Map

这篇博客详细总结了如何使用Gson库处理JSON数据中的List和Map类型。在List部分,展示了基本用法及泛型应用的实例。而在Map部分,不仅有简单使用的例子,还涵盖了使用泛型进行解析的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.List

 简单使用

@Test
	public void testList() {
		List list = new ArrayList();
		list.add("one");
		list.add(122);
		String json = gson.toJson(list);
		System.out.println("json->" + json);
		
		List list2 = gson.fromJson(json , List.class);
		for(Object each : list2) {
			System.out.println(each);
		}
		
	}

结果:


处理泛型:

       class Person {
		public int id;
		public String name;
		
		public Person(int _id , String _name) {
			this.id = _id;
			this.name = _name;
		}
		
		public String toString() {
			return "id->" + id + ",name->" + name;
		}
	}
	@Test
	public void testList2() {
		List<Person> persons = new ArrayList<Person>();
		persons.add(new Person(1 , "one"));
		persons.add(new Person(2 , "two"));
		
		String json = gson.toJson(persons);
		System.out.println("json->" + json);
		
		Type type = new TypeToken<List<Person>>() {}.getType(); 
		List<Person> anotherPersons = gson.fromJson(json , type);
		for(Person each : anotherPersons) {
			System.out.println(each);
		}
		
	}

结果:


2.Map

简单使用

@Test
	public void testMap() {
		Map map = new HashMap();
		map.put("one" , "路飞");
		map.put("two" , 999);
		
		String json = gson.toJson(map);
		System.out.println(json);
		
		Map map2 = gson.fromJson(json , Map.class);
		for(Object each : map2.entrySet()) {
			System.out.println(each);
		}
	}

结果显示:


使用泛型:

        @Test
	public void testMap2() {
		Map<String , Person> map = new HashMap<String , Person>();
		map.put("first" , new Person(1 , "路飞"));
		map.put("second", new Person(2 , "索隆"));
		
		String json = gson.toJson(map);
		System.out.println("json->" + json);
		
		Type type = new TypeToken<Map<String , Person>>() {}.getType(); 
		Map<String , Person> map2 = gson.fromJson(json , type);
		for(String key : map2.keySet()) {
			System.out.println(key + "->" + map2.get(key));
		}
		
	}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值