Andy 胡

导航

Json2:使用gson解析为List和Map

import java.lang.reflect.Type;
import java.util.List;

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

public class Json解析成List {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        sb.append(" {'name':'张辽','power':93},");
        sb.append(" {'name':'徐晃','power':94},");
        sb.append(" {'name':'张郃','power':91},");
        sb.append(" {'name':'于禁','power':90},");
        sb.append(" {'name':'乐进','power':87}");
        sb.append("]");
        String json = sb.toString();

        Gson gson = new Gson();
        // 将 json 转化成List泛型
        Type t = new TypeToken<List<People>>() {}.getType();
        List<People> ps = gson.fromJson(json, t);

        System.out.println(ps);
        System.out.println(ps.get(1).getName() + "," + ps.get(1).getPower());
    }
}

运行结果:

[People@4770a4d0, People@34547854, People@15a7eda3, People@43e27370, People@4808e0e1]
徐晃,94

import java.util.Map;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Json解析成map {

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append(" '锦马超':{'name':'马超','Power':96},");
        sb.append(" '猛张飞':{'name':'张飞','Power':96}");
        sb.append("}");
        String json = sb.toString();

        Gson gson = new Gson();
        // 将json转化成 Map泛型
        Type t = new TypeToken<Map<String, People>>() {
        }.getType();
        Map<String, People> map = gson.fromJson(json, t);
        System.out.println(map);
    }
}

运行结果:

{锦马超=People@8c3d026, 猛张飞=People@6f967348}

 

辅助类:

public class People {
    private String name;
    private int power;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPower() {
        return power;
    }

    public void setPower(int power) {
        this.power = power;
    }
}

 

posted on 2017-02-07 21:22  talkwah  阅读(708)  评论(0编辑  收藏  举报