1. FastJson是阿里巴巴的开源JAR包 是速度最快的JSON解析包 先去下载号这个JAR包 添加到我们的项目中
然后看看FastJson的基本方法:
public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
public static final T parseObject(String text, Class clazz); // 把JSON文本parse为JavaBean
public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
public static final List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合
public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray。
我一般只用到前面几个 把JSON文本转化成jsonObject 然后调用JSONObject 的方法getString(key) 等等 来获取我们需要的属性值。
或者转化成jsonArray 遍历获得我们的jsonObject 总的来说其实跟java解析JSON是差不多的 对jsonSbject后期处理是一样的 只是解析过程不一样而已
2. FastJson解析实例:
要解析的JSON数据: 是北京的近几天的天气情况:
{"weatherinfo":{"city":"北京","city_en":"beijing","date_y":"2014年3月4日","date":"","week":"星期二","fchh":"11","cityid":"101010100","temp1":"8℃~-3℃","temp2":"8℃~-3℃","temp3":"7℃~-3℃","temp4":"8℃~-1℃","temp5":"10℃~1℃","temp6":"10℃~2℃","tempF1":"46.4℉~26.6℉","tempF2":"46.4℉~26.6℉","tempF3":"44.6℉~26.6℉","tempF4":"46.4℉~30.2℉","tempF5":"50℉~33.8℉","tempF6":"50℉~35.6℉","weather1":"晴","weather2":"晴","weather3":"晴","weather4":"晴转多云","weather5":"多云","weather6":"多云","img1":"0","img2":"99","img3":"0","img4":"99","img5":"0","img6":"99","img7":"0","img8":"1","img9":"1","img10":"99","img11":"1","img12":"99","img_single":"0","img_title1":"晴","img_title2":"晴","img_title3":"晴","img_title4":"晴","img_title5":"晴","img_title6":"晴","img_title7":"晴","img_title8":"多云","img_title9":"多云","img_title10":"多云","img_title11":"多云","img_title12":"多云","img_title_single":"晴","wind1":"北风4-5级转微风","wind2":"微风","wind3":"微风","wind4":"微风","wind5":"微风","wind6":"微风","fx1":"北风","fx2":"微风","fl1":"4-5级转小于3级","fl2":"小于3级","fl3":"小于3级","fl4":"小于3级","fl5":"小于3级","fl6":"小于3级","index":"寒冷","index_d":"天气寒冷,建议着厚羽绒服、毛皮大衣加厚毛衣等隆冬服装。年老体弱者尤其要注意保暖防冻。","index48":"冷","index48_d":"天气冷,建议着棉服、羽绒服、皮夹克加羊毛衫等冬季服装。年老体弱者宜着厚棉衣、冬大衣或厚羽绒服。","index_uv":"中等","index48_uv":"中等","index_xc":"较适宜","index_tr":"一般","index_co":"较舒适","st1":"7","st2":"-3","st3":"8","st4":"0","st5":"7","st6":"-1","index_cl":"较不宜","index_ls":"基本适宜","index_ag":"易发"}}
写一个FastJson的解析工具类:
public class JsonService {
public static JSONObject getWeather(String jsonStr){
JSONObject jsonObject = JSON.parseObject(jsonStr);
return jsonObject;
}
}
然后就可以进行解析了 我们要得到城市名称:
jsonString = HttpUtils.httpjson(path);
JSONObject jsonObject = JsonService.getWeather(jsonString);// FastJson的用武之地
JSONObject object = jsonObject.getJSONObject("weatherinfo");// 从这里开始是我们自己的处理
String cityname = object.getString("city");
System.out.println("第一个方法得到:----"+cityname);// 打印出: 北京
OVER!! 就这么简单! 别想那么复杂