利用Gson解析多层嵌套的JSON数据

数据实例:

{
    "error": 0,
    "status": "success",
    "results": [
        {
            "currentCity": "青岛",
            "index": [
                {
                    "title": "穿衣",
                    "zs": "较冷",
                    "tipt": "穿衣指数",
                    "des": "建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。"
                },
                {
                    "title": "紫外线强度",
                    "zs": "中等",
                    "tipt": "紫外线强度指数",
                    "des": "属中等强度紫外线辐射天气,外出时建议涂擦SPF高于15、PA+的防晒护肤品,戴帽子、太阳镜。"
                }
            ]

        }
    ]
}

代码如下:

package com.iteam.test;

import com.google.gson.Gson;
import com.iteam.where.bean.JsonBean;

public class BmobTest {

    public static void main(String[] args) {

        String s = "{\"error\":0,\"status\":\"success\",\"results\":[{\"currentCity\":\"青岛\",\"index\":[{\"title\":\"穿衣\",\"zs\":\"较冷\",\"tipt\":\"穿衣指数\",\"des\":\"建议着厚外套加毛衣等服装。年老体弱者宜着大衣、呢外套加羊毛衫。\"},{\"title\":\"紫外线强度\",\"zs\":\"最弱\",\"tipt\":\"紫外线强度指数\",\"des\":\"属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。\"}]}]}";    
        Gson gson = new Gson();    
        //把JSON数据转化为对象
        JsonBean jsonBean = gson.fromJson(s, JsonBean.class);

    }
}

按照JSON数据来写的bean文件:

package com.iteam.where.bean;

import java.util.List;

public class JsonBean {

private int error;
private String status;
private List results;
public int getError() {
    return error;
}
public void setError(int error) {
    this.error = error;
}
public String getStatus() {
    return status;
}
public void setStatus(String status) {
    this.status = status;
}
public List getResults() {
    return results;
}
public void setResults(List results) {
    this.results = results;
}
}



import java.util.List;

public class Results {

private String currentCity;
private List index;
public String getCurrentCity() {
    return currentCity;
}
public void setCurrentCity(String currentCity) {
    this.currentCity = currentCity;
}
public List getIndex() {
    return index;
}
public void setIndex(List index) {
    this.index = index;
}

}



public class Index {

private String title;
private String zs;
private String tipt;
private String des;
public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getZs() {
    return zs;
}
public void setZs(String zs) {
    this.zs = zs;
}
public String getTipt() {
    return tipt;
}
public void setTipt(String tipt) {
    this.tipt = tipt;
}
public String getDes() {
    return des;
}
public void setDes(String des) {
    this.des = des;
}

}

你可能感兴趣的:(Java,gson,json,数据)