Json轉換利器Gson之實例三-Map處理(上)--(LinkedHashMap)--(手動解析-TypeToken)

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, 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, 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, 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, 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]  
轉載地址:http://blog.csdn.net/lk_blog/article/details/7685210)

http://www.xuebuyuan.com/2115916.html

參考:http://blog.csdn.net/Caesardadi/article/category/1351535

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章