• 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;
            }
            
            
        }
    
    }
  • 相关阅读:
    【转】Paxos算法深入分析
    GOLANG 反射法则
    谈谈Java中整数类型(short int long)的存储方式
    大型网站架构学习笔记
    Java并发编程基础
    spring 优点
    JavaScript 中,num = num || 1 这种写法有哪些优缺点?
    javascript删除字符串最后一个字符
    javascript中字符串拼接详解
    JSONObject、JSONArray
  • 原文地址:https://www.cnblogs.com/yshyee/p/4393765.html
Copyright © 2020-2023  润新知