jason字符串解析

public class TestJson {
public static void main(String[] args) {
//要解析的对象
String json = “{ ‘desc’: ‘OK’, ” +
“‘status’: 1000, ” +
“‘data’: { ‘wendu’: ‘20’,” +
” ‘ganmao’: ‘相对于今天将会出现大幅度降温,易发生感冒,请注意适当增加衣服,加强自我防护避免感冒。’, ” +
“‘forecast’: [ { ‘fengxiang’: ‘北风’, ‘fengli’: ‘3-4级’, ‘high’: ‘高温 27℃’, ‘type’: ‘中雨’, ‘low’: ‘低温 19℃’, ‘date’: ‘6日星期五’ }, ” +
“{ ‘fengxiang’: ‘北风’, ‘fengli’: ‘微风级’, ‘high’: ‘高温 23℃’, ‘type’: ‘大雨’, ‘low’: ‘低温 17℃’, ‘date’: ‘7日星期六’ }, ” +
“{ ‘fengxiang’: ‘北风’, ‘fengli’: ‘微风级’, ‘high’: ‘高温 26℃’, ‘type’: ‘小雨’, ‘low’: ‘低温 17℃’, ‘date’: ‘8日星期天’ }, ” +
“{ ‘fengxiang’: ‘南风’, ‘fengli’: ‘微风级’, ‘high’: ‘高温 27℃’, ‘type’: ‘多云’, ‘low’: ‘低温 15℃’, ‘date’: ‘9日星期一’ },” +
” { ‘fengxiang’: ‘南风’, ‘fengli’: ‘微风级’, ‘high’: ‘高温 29℃’, ‘type’: ‘多云’, ‘low’: ‘低温 16℃’, ‘date’: ‘10日星期二’ } ], ” +
“‘yesterday’: { ‘fl’: ‘微风’, ‘fx’: ‘北风’, ‘high’: ‘高温 33℃’, ‘type’: ‘阴’, ‘low’: ‘低温 22℃’, ‘date’: ‘5日星期四’ },” +
” ‘aqi’: ‘58’,” +
” ‘city’: ‘成都’ } }”;

    System.out.println("==================================================================================");
    //将解析的值存入对象之中
    Weather weather=new Weather();
    Data data=new Data();
    Forecast forecast=new Forecast();
    //将节点对象转换成Object对象
    JSONObject jsonObject1 = JSONObject.parseObject(json);
    //获取到data对象
    JSONObject data1 = jsonObject1.getJSONObject("data");
    //通过data对象获取到forecast数组
    JSONArray jsonArray = data1.getJSONArray("forecast");
    //遍历jsonArray数组,取出数组中的值
    for (int i = 0; i < jsonArray.size(); i++) {
        JSONObject object = (JSONObject) jsonArray.get(i);
        forecast.setFengxiang(object.getString("fengxiang"));
        forecast.setFengli(object.getString("fengli"));
        forecast.setHigh(object.getString("high"));
        forecast.setDate(object.getString("date"));
    }
    System.out.println("===================================================================================");
    //获取desc的值
    Object desc = jsonObject1.get("desc");
    System.out.println(desc);
    //获取ganmao的值
    Object ganmao = data1.get("ganmao");
    System.out.println(ganmao);
    //通过数组下标获取某个对象
    JSONObject jsonObject = (JSONObject) jsonArray.get(0);
    //通过key取到value值
    String type = jsonObject.getString("type");
    Object low = jsonObject.get("low");
    System.out.println(type);
    System.out.println(low);
}

}

做为一个菜鸟,第一次发。不喜勿喷,有错忘大家指正……

你可能感兴趣的:(jason字符串解析)