Json解析3--Gson解析多种json样式

来源:互联网 发布:股票数据分析软件 编辑:程序博客网 时间:2024/05/16 14:42

1. 单个数据对象

{"dbopt":"insert","probeid":"123456","date":"Feb 1, 2000 12:00:00 AM","size":"666"}
代码:
import java.util.Date;public class HeheBean {    private String dbopt;    private String probeid;    private Date date;    private String size;    public String getDbopt() {        return dbopt;    }    public void setDbopt(String dbopt) {        this.dbopt = dbopt;    }    public String getProbeid() {        return probeid;    }    public void setProbeid(String probeid) {        this.probeid = probeid;    }    public Date getDate() {        return date;    }    public void setDate(Date date) {        this.date = date;    }        public String getSize() {        return size;    }    public void setSize(String size) {        this.size = size;    }}
import com.google.gson.Gson;public class JsonToHehe {    public static void main(String[] args) {        String json = "{\"dbopt\":\"insert\",\"probeid\":\"123456\",\"date\":\"Feb 1, 2000 12:00:00 AM\",\"size\":\"666\"}";            Gson gson = new Gson();        HeheBean hehe = gson.fromJson(json, HeheBean.class);        System.out.println("dbopt = " + hehe.getDbopt());        System.out.println("probeid = " + hehe.getProbeid());        System.out.println("date = " + hehe.getDate());        System.out.println("size = " + hehe.getSize());    }}
运行结果:

dbopt = insert
probeid = 123456
date = Tue Feb 01 00:00:00 CST 2000
size = 666


2. 嵌套多组数据

案例一:

{"dbopt": "insert", "probeid": "123456", "type": "type", "data": {"disk": [{"rate": 51.1, "total": 20091629568, "temperature": 100.0}], "cpu": [{"rate": 0.0, "num": "0", "temperature": 100.0}, {"rate": 1.0, "num": "1", "temperature": 100.0}], "memory": [{"totoal": 1056534528, "rate": 43.1}]}, "size": 666}
万能解析代码,挺像xpath解析xml的:
import java.util.List;public class Parse {public Data data;public static class Data{public List<Disk> disk;public static class Disk{public String total;} }}
import com.google.gson.Gson;public class test {public static void main(String args[]){String json="{\"dbopt\": \"insert\", \"probeid\": \"123456\", \"type\": \"type\"," +" \"data\": {\"disk\": [{\"rate\": 51.1, \"total\": 20091629568, " +"\"temperature\": 100.0}], \"cpu\": [{\"rate\": 0.0, \"num\": \"0\", \"temperature\": 100.0}, " +"{\"rate\": 1.0, \"num\": \"1\", \"temperature\": 100.0}], \"memory\": " +"[{\"totoal\": 1056534528, \"rate\": 43.1}]}, \"size\": 666}";Gson gson=new Gson();Parse p=gson.fromJson(json, Parse.class);System.out.println(p.data.disk.get(0).total);}}
运行结果:
20091629568


案例二(该案例来自http://bbs.csdn.net/topics/390974922?page=1):

[    {        "code": 200,        "response": [            {                "page": 1,                "user": [                    {                        "name": "张三",                        "age": 20,                        "sex": "男"                    },                    {                        "name": "李四",                        "age": 21,                        "sex": "男"                    },                    {                        "name": "王五",                        "age": 22,                        "sex": "男"                    }                ]            }        ]    }]
代码:

import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.lang.reflect.InvocationTargetException;import java.util.Arrays;import com.google.gson.Gson; public class Test {     /**     * @param args     * @throws IOException      * @throws InvocationTargetException      * @throws IllegalAccessException      * @throws NoSuchMethodException      * @throws IllegalArgumentException      * @throws SecurityException      */    public static void main(String[] args) throws Exception{        String str=getJsonStr();        Gson gson = new Gson();        ResultMsg[] resultMsgArray=gson.fromJson(str, ResultMsg[].class);        printlnMsg(resultMsgArray);    }         /**     * 获得要转换的JSON字符串<br>     * 这边为了方面我直接读的我本地的文件内容为你要转换的json字符串     * @return     * @throws IOException     */    private static String getJsonStr() throws IOException{        StringBuffer sbf = new StringBuffer();        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("json.txt"),"UTF-8"));        //json字符串        String str="";        while((str=reader.readLine())!=null){            sbf.append(str);        }        reader.close();        return sbf.toString();    }         private static void printlnMsg(ResultMsg[] resultMsgArray){        if(null!=resultMsgArray){            System.out.println("结果:"+Arrays.toString(resultMsgArray));        }    }} class ResultMsg{    private Response[] response;    private String code;         public String getCode() {        return code;    }    public void setCode(String code) {        this.code = code;    }    public Response[] getResponse() {        return response;    }    public void setResponse(Response[] response) {        this.response = response;    }    @Override    public String toString() {        return "ResultMsg [response=" + Arrays.toString(response) + ", code="                + code + "]";    }}class Response{    private String page;    private User[] user;    public String getPage() {        return page;    }    public void setPage(String page) {        this.page = page;    }    public User[] getUser() {        return user;    }    public void setUser(User[] user) {        this.user = user;    }    @Override    public String toString() {        return "Response [page=" + page + ", user=" + Arrays.toString(user)                + "]";    }}class User {    private String name;    private String age;    private String sex;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getAge() {        return age;    }    public void setAge(String age) {        this.age = age;    }    public String getSex() {        return sex;    }    public void setSex(String sex) {        this.sex = sex;    }    @Override    public String toString() {        return "User [name=" + name + ", age=" + age + ", sex=" + sex + "]";    }     }
运行结果:

结果:[ResultMsg [response=[Response [page=1, user=[User [name=张三, age=20, sex=男], User [name=李四, age=21, sex=男], User [name=王五, age=22, sex=男]]]], code=200]]


原创粉丝点击