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;
    }
}

 

转载于:https://www.cnblogs.com/AndyHoo/p/6375971.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值