json解析方法之gson解析,简单粗暴。

  • 先看一个简单的例子:
String object="{\"id\":\"123\",\"name\":\"zhangsan\"}";//{"id":"123","name":"张三"}
System.out.println(object);
Bean bean=new Bean();
//将一个jsonObject转化为一个Bean对象
bean=new Gson().fromJson(object, Bean.class);
System.out.println("id:"+bean.getId());
System.out.println("name:"+bean.getName());
public class Bean {
    private String id;
    private String name;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}
  • 稍微难一点的例子
String obj="{\"id\":\"001\",\"subject\":[{\"a1\":\"a1\"},{\"a2\":\"a2\"}],\"name\":{\"c\":\"c\",\"d\":\"d\"}}";
        //{"id":"001","subject":[{"a1":"a1"},{"a2":"a2"}],"name":{"c":"c","d":"d"}}
System.out.println(obj);
Gson gson=new Gson();
JsonBean jsonBean=gson.fromJson(obj, JsonBean.class);
System.out.println("id:"+jsonBean.getId());
System.out.println("subject..a1.."+jsonBean.getSubject().get(0).a1);
System.out.println("subject....a2..."+jsonBean.getSubject().get(1).a2);
System.out.println("name...c..."+jsonBean.getName().c);
System.out.println("name...d..."+jsonBean.getName().d);
/***序列化的javabean
 * 采用内部类的形式看的清楚些*/
public class JsonBean {
    //{"id":"001","subject":[{"a1":"a1"},{"a2":"a2"}],"name":{"c":"c","d":"d"}}
    public String id;
    /***Json数组是一个list*/
    public Listsubject;
    /***json对象是一个内部类*/
    public Name name;
    /**内部类必须为static,且属性必须和key相同*/
    public static class A{
        public String a1;
        public String a2;
    }
    public static class Name{
        public String c;
        public String d;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public List getSubject() {
        return subject;
    }
    public void setSubject(List subject) {
        this.subject = subject;
    }
    public Name getName() {
        return name;
    }
    public void setName(Name name) {
        this.name = name;
    }
}

注意几点:

  1. 内部嵌套的类必须是static的,要不然解析会出错;
  2. 类里面的属性名必须跟Json字段里面的Key是一模一样的;
  3. 内部嵌套的json数组必须用List,jSONObject必须用内部类;

你可能感兴趣的:(android)