Java工具类--JSON解析(以百度天气为例)

随着JSON的广泛应用,解析JSON也成了程序员的一项基本技能。今天介绍JSON解析利器-Gson和fastjson

Gson是谷歌封装的JSON解析类库,使用方便,fastjson是阿里巴巴的产品,使用也非常方便,我问小满喜欢用哪个?他说Gson,why?因为Gson单词少,写着方便!小满,我觉得你说的很有道理。

  1. fromJson(String json, Class <T> classOfT)方法来实现从Json到java对象的转换。
  2. toJson(Object src)方法实现对象转化为JSON字符串。

首先看一下fromJson方法

通常我们都会从网络中获取数据,今天介绍一个获取百度天气的

http://api.map.baidu.com/telematics/v3/weather?location=CITY_NAME&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH

其中CITY_NAME就是城市名称,通过这个就可以获取到对应城市的天气了。下面就来解析它。

首先看一下天气的数据结构

这里写图片描述
这里写图片描述

下面我们分析一下这个数据结构,再根据数据结构定义好对象就Ok啦

根元素

这里写图片描述

以下是我定义的根对象

public class WeatherInfo {
    private int error;
    private String status;
    private String date;
    private List<WeatherResults> results;
    //省去setter和getter方法
}

再定义
List型的results

这里写图片描述

public class WeatherResults {
    private String currentCity;
    private String pm25;
    private List<WeatherSuggest> index;
    private List<WeatherDay> weather_data;
    //省去setter和getter方法
}

在WeatherResults中再定义两个List型的index和weather_data

这里写图片描述

public class WeatherSuggest {
    private String title;
    private String zs;
    private String tipt;
    private String des;
    //省去setter和getter方法
}

public class WeatherDay {
    private String date;
    private String dayPictureUrl;
    private String nightPictureUrl;
    private String weather;
    private String wind;
    private String temperature;
    //省去setter和getter方法
}

JSON数据太长,请访问
http://api.map.baidu.com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH
获取JSON数据,有了JSON数据下一步就是将JSON数据映射到对应的对象上
核心代码只需两行

        String city = URLEncoder.encode("北京", "UTF-8");
        String url = "http://api.map.baidu.com/telematics/v3/weather?location=CITY&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH".replace("CITY", city);
        //调用一个发送http请求的方法,后面会有博客写如何发送http请求
        //发送请求后就得到了json字符串
        String jsonStr = sendGet(url);
        //JSON的核心代码
        Gson gson = new GsonBuilder().create();
        WeatherInfo weatherInfo = gson.fromJson(jsonStr, WeatherInfo.class);
        //只需两行代码,就完成了json字符串到对象的映射
        //如果除去Gson gson = new GsonBuilder().create();只有一行代码,是不是很方便

使用fastjson的方法

    WeatherInfo weatherInfo = JSON.parseObject(jsonStr, WeatherInfo.class);//只需一行

有了对象,如果需要输出其中的数据,就很简单了。
假设要得到紫外线强度的des

    weatherInfo.getResults().get(0).getIndex().get(5).getDes()

得到数据

紫外线强度较弱,建议出门前涂擦SPF在12-15之间、PA+的防晒护肤品。

要得到天气情况

    WeatherInfo weatherInfo = JSON.parseObject(jsonStr, WeatherInfo.class);
    List<WeatherDay> weatherDatas = weatherInfo.getResults().get(0).getWeather_data();
    System.out.println(weatherInfo.getResults().get(0).getCurrentCity());
        for(WeatherDay weatherDay:weatherDatas){
            System.out.print(weatherDay.getDate()+" ");
            System.out.print(weatherDay.getWeather());
            System.out.println(weatherDay.getTemperature());

        }

输出结果

北京
周三 11月25日 (实时:-7℃) 晴-1 ~ -9℃
周四 晴转多云0 ~ -8℃
周五 多云转晴1 ~ -6℃
周六 多云3 ~ -5℃

再看一下toJson方法

toJson方法更简单,有了对象,直接调用toJson即可得到JSON字符串

String json = gson.toJson(weatherInfo);

使用fastjson的方法

String json = JSON.toJSONString(weatherInfo);

使用fastjson会乱序,准确的说是fastjson对其进行了排序,而不是按照字段的顺序。

就可以得到同访问
http://api.map.baidu.com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH
一样的字符串

java解析json字符串。 commons-beanutils-1.9.0 commons-collections-3.2.1 commons-lang-2.6 commons-logging-1.1.3 ezmorph-1.0.6 json-lib-2.4-jdk15 demo: package com; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import net.sf.ezmorph.object.DateMorpher; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.JSONUtils; public class Jsontest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub JSONObject jsonObj = new JSONObject(); jsonObj.put("name", "hzj"); jsonObj.put("sex", "female"); System.out.println(jsonObj); } public static Object jsonToBean(String jsonString, Class cla) { JSONObject jsonObj = null; try { setDateFormat2Java(); jsonObj = JSONObject.fromObject(jsonString); } catch (Exception ex) { ex.printStackTrace(); } return JSONObject.toBean(jsonObj, cla); } public static Object jsonToBean(String jsonString, Class cla, Map map) { JSONObject jsonObj = null; try { setDateFormat2Java(); jsonObj = JSONObject.fromObject(jsonString); } catch (Exception ex) { ex.printStackTrace(); } return JSONObject.toBean(jsonObj, cla, map); } public static Object[] jsonToArray(String jsonString, Class cla) { Object[] arrObj = null; try { setDateFormat2Java(); JSONArray array = JSONArray.fromObject(jsonString); arrObj = new Object[array.size()]; for (int i = 0; i < array.size(); i++) { JSONObject jsonObject = array.getJSONObject(i); arrObj[i] = JSONObject.toBean(jsonObject, cla); } } catch (Exception ex) { ex.printStackTrace(); } return arrObj; } public static Object[] jsonToArray(String jsonString, Class cla, Map map) { Object[] arrObj = null; try { setDateFormat2Java(); JSONArray array = JSONArray.fromObject(jsonString); arrObj = new Object[array.size()]; for (int i = 0; i < array.size(); i++) { JSONObject jsonObject = array.getJSONObject(i); arrObj[i] = JSONObject.toBean(jsonObject, cla, map); } } catch (Exception ex) { ex.printStackTrace(); } return arrObj; } public static List jsonToList(String jsonString, Class cla) { List list = null; try { setDateFormat2Java(); JSONArray array = JSONArray.fromObject(jsonString); list = new ArrayList(); for (Iterator iter = array.iterator(); iter.hasNext();) { JSONObject jsonObject = (JSONObject) iter.next(); list.add(JSONObject.toBean(jsonObject, cla)); } } catch (Exception ex) { ex.printStackTrace(); } return list; } public static List jsonToList(String jsonString, Class cla, Map map) { List list = null; try { setDateFormat2Java(); JSONArray array = JSONArray.fromObject(jsonString); list = new ArrayList(); for (Iterator iter = array.iterator(); iter.hasNext();) { JSONObject jsonObject = (JSONObject) iter.next(); list.add(JSONObject.toBean(jsonObject, cla, map)); } } catch (Exception ex) { ex.printStackTrace(); } return list; } public static Map jsonToMap(String jsonString) { Map map = null; try { setDateFormat2Java(); JSONObject jsonObject = JSONObject.fromObject(jsonString); map = new HashMap(); for (Iterator iter = jsonObject.keys(); iter.hasNext();) { String key = (String) iter.next(); map.put(key, jsonObject.get(key)); } } catch (Exception ex) { ex.printStackTrace(); } return map; } public static Object[] jsonToArray(String jsonString) { JSONArray jsonArray = JSONArray.fromObject(jsonString); return jsonArray.toArray(); } public static void setDateFormat2Java() { JSONUtils.getMorpherRegistry().registerMorpher( new DateMorpher(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" })); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值