Gson JsonParser的使用
package iotest; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author yan * @version V1.0 * @desc */ public class Iotest { public static void main(String[] args) { Result result = new Result(); result.setNo(1); result.setMsg("OK"); List<String> list = new ArrayList<String>(); list.add("123"); list.add("234"); list.add("345"); result.setObj(list); Gson gson = new Gson(); String json = gson.toJson(result); System.out.println(json); /** * {"no":1,"msg":"OK","obj":["123","234","345"]} */ JsonParser jp = new JsonParser(); JsonObject jsonObj = jp.parse(json).getAsJsonObject(); int no = jsonObj.get("no").getAsInt(); System.out.println("no:"+no); String msg = jsonObj.get("msg").getAsString(); System.out.println("msg:"+msg); JsonArray jsonArray = jsonObj.get("obj").getAsJsonArray(); Iterator<JsonElement> iter = jsonArray.iterator(); List<String> objs = new ArrayList<String>(); while(iter.hasNext()){ objs.add(iter.next().getAsString()); } for(String s:objs){ System.out.println("==s:"+s); } } static class Result{ private Integer no; private String msg; private Object obj; public Integer getNo() { return no; } public void setNo(Integer no) { this.no = no; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getObj() { return obj; } public void setObj(Object obj) { this.obj = obj; } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。