欢迎光临Software MyZone,有问题可留言或到站点论坛发帖,争取第一时间帮忙解决 || 站点论坛:火龙论坛 || 淘宝小店:应小心的易淘屋 【欢迎大家提建设性意见】

Json转换利器Gson之实例三-Map处理(上)

欢迎热爱编程的朋友们参与到cocos2d-x编程中,为了给大家提供良好的交流环境,网站以开启QQ群
Software MyZone:66202765(群号,欢迎加入,若满,请加1群)
Software MyZone 1群(2dx):286504621
Software MyZone 2群(山东):204954191
Software MyZone【Java群】:162865493
【加群请写:Software MyZone或者是firedragonpzy】
淘宝店:【应小心的易淘屋】初次开店,大家多多支持……
群论坛:【火龙论坛】正试运营阶段,欢迎大家多提些建设性意见……
群问答:【火龙问答】正试运营阶段,欢迎大家多提些建设性意见……
摘自:http://blog.csdn.net/lk_blog/article/details/7685210

我的digitalocean推广链接:https://www.digitalocean.com/?refcode=65dfdb158f1a,Everyone you refer gets $10 in credit,从此链接注册,你将获得10美元。

Map的存储结构式Key/Value形式,Key 和 Value可以是普通类型,也可以是自己写的JavaBean(本文),还可以是带有泛型的List(下一篇博客).本例中您要重点看如何将Json转回为普通JavaBean对象时TypeToken的定义.

实体类:

 

public class Point {
	private int x;
	private int y;

	public Point(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	@Override
	public String toString() {
		return "Point [x=" + x + ", y=" + y + "]";
	}

}

测试类:

 

import java.util.LinkedHashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class GsonTest3 {

	public static void main(String[] args) {
		Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
				.create();

		Map<point , String> map1 = new LinkedHashMap</point><point , String>();// 使用LinkedHashMap将结果按先进先出顺序排列
		map1.put(new Point(5, 6), "a");
		map1.put(new Point(8, 8), "b");
		String s = gson.toJson(map1);
		System.out.println(s);// 结果:[[{"x":5,"y":6},"a"],[{"x":8,"y":8},"b"]]

		Map</point><point , String> retMap = gson.fromJson(s,
				new TypeToken<map <Point, String>>() {
				}.getType());
		for (Point p : retMap.keySet()) {
			System.out.println("key:" + p + " values:" + retMap.get(p));
		}
		System.out.println(retMap);

		System.out.println("----------------------------------");
		Map<string , Point> map2 = new LinkedHashMap</string><string , Point>();
		map2.put("a", new Point(3, 4));
		map2.put("b", new Point(5, 6));
		String s2 = gson.toJson(map2);
		System.out.println(s2);

		Map</string><string , Point> retMap2 = gson.fromJson(s2,
				new TypeToken<map <String, Point>>() {
				}.getType());
		for (String key : retMap2.keySet()) {
			System.out.println("key:" + key + " values:" + retMap2.get(key));
		}

	}
}

结果:

[[{"x":5,"y":6},"a"],[{"x":8,"y":8},"b"]]
key:Point [x=5, y=6] values:a
key:Point [x=8, y=8] values:b
{Point [x=5, y=6]=a, Point [x=8, y=8]=b}
———————————-
{“a”:{“x”:3,”y”:4},”b”:{“x”:5,”y”:6}}
key:a values:Point [x=3, y=4]
key:b values:Point [x=5, y=6]

  1. Json转换利器Gson之实例一-简单对象转化和带泛型的List转化
  2. Json转换利器Gson之实例二-Gson注解和GsonBuilder
  3. Json转换利器Gson之实例三-Map处理(上)
  4. Json转换利器Gson之实例四-Map处理(下)
  5. Json转换利器Gson之实例五-实际开发中的特殊需求处理
  6. Json转换利器Gson之实例六-注册TypeAdapter及处理Enum类型

Tags: ,

发表评论