在日常编写代码,调用接口的时候,难免会遇到一些json数据需要处理或者返回一些json数据给别人,那么怎么样才能方便的操作呢?
准备工作:
导入gson-2.6.2.jar包
解析json代码:
public static void main(String[] args) { try { //第一种 String result="";//这里是你的json字符串信息 JsonObject jo = new JsonParser().parse(result).getAsJsonObject();//将字符串转化成json格式 JsonArray ja = jo.get("data").getAsJsonArray();//获取result中参数为“data”的值,这里我假设data是一个数组 for (JsonElement je:ja) { JsonObject datajo = je.getAsJsonObject();//遍历“data”中的每个对象 String id = datajo.get("Id").getAsString();//获取指定的值,这里我随便写了ID } //第二种 String result="";//这里是你的json字符串信息 Map<String,Object> map = new HashMap<>();//创建一个map Gson gson = new Gson(); map = gson.fromJson(result,map.getClass());//直接强转,然后通过map取值 } catch (RemoteException e) { e.printStackTrace(); } }