Gson简单使用(持续补充)

直接上代码:

package com.lishiots.cloud.ots.web.shiro;

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

/**
 * Created by Chaofan at 2018/7/12 17:04
 * email:[email protected]
 **/
public class GsonDemo {

    public static void main(String[] arg){
        Gson gson = new Gson();
        Map map = new HashMap<>();
        map.put("code","8200");
        map.put("msg","success");
        map.put("data","哈哈哈");

        // 1.Object转json
        String json = gson.toJson(map);

        // 2.Gson操作json字符串
        JsonElement element = new JsonParser().parse(json);
        JsonElement elementData = element.getAsJsonObject().get("data");

        // 3.json转Object
        Type type = new TypeToken>(){}.getType();
        HashMap json2map = gson.fromJson(json,type);
    }

}

你可能感兴趣的:(java)