JAVA简便解析json文件
首先放上我要解析的json文件:
{ "resultcode":"200", "reason":"Success", "result":{ "data":[ { "id":"14", "title":"红烧肉", "tags":"家常菜;老年人;咸;半小时-1小时;青少年;白领;红烧;1-2人;炒锅", "imtro":"加了鹌鹑蛋,祝大家岁岁平“鹌”。", "ingredients":"五花肉,250g;萝卜,100g;鹌鹑蛋,20个", "burden":"油,适量;盐,适量", "albums":[ "http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/t\/0\/14_359794.jpg" ], "steps":[ { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_706ca81e0bbecefe.jpg", "step":"1.带皮五花肉 ,鹌鹑蛋,白萝卜备用。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_dc89a7e8f2823202.jpg", "step":"2.配料备用。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_ae5efcd7698c7a51.jpg", "step":"3.鹌鹑蛋煮熟后去皮,备用。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_6246ae9cde95a443.jpg", "step":"4.白萝卜洗净,切大块。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_fa36e18ba88ba812.jpg", "step":"5.五花肉,洗净切大块。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_fb6017cd9ea66698.jpg", "step":"6.焯水后备用。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_79b1cc9fb722b4dd.jpg", "step":"7.油锅烧热,下入肉块。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_0a45336653b0eb33.jpg", "step":"8.煎到微黄。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_cb483431930bb8cd.jpg", "step":"9.加入白糖。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_93eababb3d6f328a.jpg", "step":"10.炒到金黄色。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_b1672001decab1dc.jpg", "step":"11.加入料酒和老抽,炒均匀。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_03ce88cb45776456.jpg", "step":"12.放入干红椒,生姜, 八角, 香叶,花椒,炒出香味后,后加入适量的水。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_5e067f35b2297a47.jpg", "step":"13.煮十几分钟后,加入萝卜和鹌鹑蛋。" }, { "img":"http:\/\/juheimg.oss-cn-hangzhou.aliyuncs.com\/cookbook\/s\/1\/14_7f8a56f9b8498703.jpg", "step":"14.再煮上十几分钟,肉和萝卜软烂,大火收汁加入适量的盐即可。" } ] } ], "totalNum":1, "pn":0, "rn":1 }, "error_code":0 }
结构大概如下:
调用api后返回的json文件就是这样,很长很乱。这份文件是一份菜谱,我现在只需要用到这里面菜名,食材,做法等信息。
先放上解析json的代码:
JSONObject object = JSONObject.fromObject(result);
JSONObject ob=object.getJSONObject("result");
JSONArray ob1=ob.getJSONArray("data");
JSONObject o2=ob1.getJSONObject(0);
JSONArray po=o2.getJSONArray("steps"); if(object.getInt("error_code")==0){
System.out.println(o2.getString("title"));
System.out.println(o2.getString("ingredients"));
System.out.println(o2.getString("burden"));
for(int i=0;i<po.size();i++){ JSONObject u=po.getJSONObject(i); System.out.println(u.get("step"));
}
通俗一点讲,解析过程分析起来就只有两点:
第一种,大括号前面的看成是JSONObject
第二种,中括号前面的看成是JSONArray
结果如下图: