The method of Java Multi-layer nesting JSON Type data
This article introduces the knowledge of "the method of Java multi-layer nesting JSON type data". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Multi-layer nested JSON type data parsing
To put it simply:
"key": "value"-- > now value is String
"key": 0-- > now value is int
"key": {"K1": "v1"}-- > when value is JSONObject
"key": [v]-- > now value is JSONArray
The following example data structure {"error": 0, "status": "success", "results": [{"currentCity": "Qingdao", "index": [{"title": "dressing", "zs": "colder" "tipt": "clothing Index", "des": "heavy coats and sweaters are recommended. The old and frail should wear a coat, a tweed coat and a woolen sweater. " }, {"title": "UV intensity", "zs": "medium", "tipt": "UV intensity Index", "des": "moderate UV radiation weather, it is recommended to apply sunscreen with SPF higher than 15 and PA+ when going out. Wear a hat and sunglasses. " }]]}} parsing code public class Test {public static void main (String [] args) {String s = "{\" error\ ": 0,\" status\ ":\" success\ ",\" results\ ": [{\" currentCity\ ":\" Qingdao\ ",\" index\ ": [{\" title\ ":\" dressing\ ",\" zs\ ":\" colder\ " \ "tipt\":\ "clothing Index\",\ "des\":\ "heavy jackets and sweaters are recommended. The old and frail should wear an overcoat, a tweed coat and a cardigan. \ "}, {\" title\ ":\" Ultraviolet intensity\ ",\" zs\ ":\" weakest\ ",\" tipt\ ":\" Ultraviolet intensity Index\ ",\" des\ ":\" is weak UV radiation weather and does not require special protection. If you are outdoors for a long time, it is recommended to apply sunscreen products with SPF between 8-12. \ "}],}]}"; JSONObject jsonObject = JSONObject.fromObject (s); / / extracted error is 0 int error = jsonObject.getInt ("error"); System.out.println ("error:" + error); / / extracted status is success String status = jsonObject.getString ("status"); System.out.println ("status:" + status) / Note: the content in results is bracketed [], so you need to convert to an object of type JSONArray JSONArray result = jsonObject.getJSONArray ("results"); for (int I = 0; I
< result.size(); i++) { //提取出currentCity为 青岛 String currentCity = result.getJSONObject(i).getString("currentCity"); System.out.println("currentCity:" + currentCity); //注意:index中的内容带有中括号[],所以要转化为JSONArray类型的对象 JSONArray index = result.getJSONObject(i).getJSONArray("index"); for (int j = 0; j < index.size(); j++) { String title = index.getJSONObject(j).getString("title"); System.out.println("title:" + title); String zs = index.getJSONObject(j).getString("zs"); System.out.println("zs:" + zs); String tipt = index.getJSONObject(j).getString("tipt"); System.out.println("tipt:" + tipt); String des = index.getJSONObject(j).getString("des"); System.out.println("des:" + des); } }}}json解析多层嵌套并转为对应类(List)Json(随便扒的格式,将就看~){ "code": 1, "message": "查询成功", "data": [ { "type": 1, "question": "地层压力与同井深的淡水静液压力之比称为地层的()。", "answer": "1", "id": 1, "description": "题目描述", "answers": [ { "isCorrect": "1", "answer_name": "A的选项内容" }, { "isCorrect": "0", "answer_name": "B的选项内容" }, { "isCorrect": 0, "answer_name": "C的选项内容" }, { "isCorect": "0", "answer_name": "D的选项内容" } ] }, { "type": 1, "question": "起钻时,产生的抽吸压力导致井底压力()。", "answer": "1", "id": 1, "description": "题目描述", "answers": [ { "isCorrect": 1, "answer_name": "A的选项内容" }, { "isCorrect": 0, "answer_name": "B的选项内容" }, { "isCorrect": 0, "answer_name": "C的选项内容" }, { "isCorrect": 0, "answer_name": "D的选项内容" } ] } ]}关键依赖 com.alibaba fastjson 1.2.72 JSONObject param = testDate(); JSONObject param1 = testHeader("QUERY"); String rDate = HealthServerHandler.getInstance().post(url,param1.toJSONString(), param.toJSONString()); //这个依赖是com.google.code.gson;因为报错原因未知(报错下面图中显示),更换了阿里的依赖 //RecOrder recOrder = new Gson().fromJson(rDate, RecOrder.class); //处理json将类填充,入库 JSONObject rDateJSON = JSONObject.parseObject(rDate); //这里获取的是"resultValue"标签下面"data"这个JSONArray JSONArray data = rDateJSON.getJSONObject("resultValue").getJSONArray("data"); //这里获取的是"resultValue"标签下面"pageInfo"这个JSONObject JSONObject pageInfo = rDateJSON.getJSONObject("resultValue").getJSONObject("pageInfo"); //PurchaseOrder 是具体接收类 List purchaseOrder = JSONArray.parseArray(data.toString(),PurchaseOrder.class); PageInfo pageInfo1 = JSONObject.parseObject(pageInfo.toString(),PageInfo.class); //茵PageInfo与PurchaseOrder并不在同一结构内,需要二次添加 for (PurchaseOrder order : purchaseOrder) { order.setPageCount(pageInfo1.getPageCount()); order.setPageNum(pageInfo1.getPageNum()); order.setTotal(pageInfo1.getTotal()); order.setPageSize(pageInfo1.getPageSize()); service.saveOrder(order); }
Package jansonDemo;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject Public class TestJSON {/ * JSON is actually also a key-value pair ("key": "value") * key must be a string, and value can be a legal JSON data type (string, number, object, array, Boolean or null) * value if it is a string, use jsonobj.getString ("key") to get * value if it is a numeral Use basic data types such as jsonobj.getIntValue ("key"), jsonobj.getFloatValue ("key"), jsonobj.getInteger ("key") and their wrapper classes to obtain * value if it is a Boolean value, use jsonobj.getBoolean ("key") and jsonobj.getBooleanValue ("key") to obtain * value if it is an array, use jsonobj.getJSONArray ("key") to obtain * value if it is an Object object, use jsonobj.get ("key") Get * value if it is a JSONObject object, use jsonobj.getJSONObject ("key") to obtain * / / * this method is used to convert an existing json string into a json object, and take out the value corresponding to the corresponding key in the object * convert the existing string into jsonobject Using the JSON.parseObject (jsonStr) method * json represents a JSONObject as long as it is {}. [] represents a JSONArray * get the JSONObject object using the JSONObject jsonobject.getJSONObject ("key") method * get the JSONArray object using the JSONObject jsonobject.getJSONArray ("key") method * / private static void strWritedToJSONObject () {/ / the following is a json sub-object nested in a json object String myJsonObj = "{\ n" + "name\":\ "runoob\" \ n "+"\ "alexa\": 10000,\ n "+"\ "sites\": {\ n "+"\ "site1\":\ "www.runoob.com\",\ n "+"\ "site2\":\ "m.runoob.com\" \ n "+"\ "site3\":\ "c.runoob.com\"\ n "+"}\ n "+"} " JSONObject jsonobj = JSON.parseObject (myJsonObj); / / convert the json string to a jsonObject object / * get the value corresponding to each key in the JSONObject, you can use methods that cannot be used according to the type you want in the actual scene * * / System.out.println (jsonobj.get ("name")) / / take out the value corresponding to name and get an object System.out.println (jsonobj.getString ("name")); / / take out the value corresponding to name and get a String System.out.println (jsonobj.getIntValue ("alexa")); / / take out the value corresponding to name and get an int System.out.println (jsonobj.get ("sites")) / / take out the value corresponding to sites, and get an object System.out.println (jsonobj.getString ("sites")); System.out.println (jsonobj.getJSONObject ("sites")); / / take out the value corresponding to sites, and get a JSONObject sub-object System.out.println (jsonobj.getJSONObject ("sites"). GetString ("site2")) / / take out the value corresponding to site2 in nested JSONObject sub-objects. You must first get JSONObject / * using getJSONObject (). Here is an array containing JSONObject objects. The array also contains json sub-objects and subarray * / String myJsonObj2 = "{\ n" + "\" name\ ":\" website\ ",\ n" + "\" num\ ": 3 \ n "+"\ "sites\": [\ n "+" {\ "name\":\ "Google\",\ "info\": [\ "Android\",\ "Google search\",\ "Google translation\"]},\ n "+" {\ "name\":\ "Runoob\" \ "info\": [\ "Rookie tutorial\",\ "Cainiao tool\",\ "Cainiao Wechat\"]},\ n "+" {\ "name\":\ "Taobao\",\ "info\": [\ "Taobao\",\ "online shopping\"}\ n "+"]\ n "+"} JSONObject jsonobj2 = JSON.parseObject (myJsonObj2); / / convert json string to jsonObject object System.out.println (jsonobj2.get ("sites")); System.out.println (jsonobj2.getString ("sites")); System.out.println (jsonobj2.getJSONArray ("sites")); / / fetch the value corresponding to sites to get a JSONOArray object / / System.out.println (jsonobj2.getJSONObject ("sites")) This method cannot be used because sites is a JSONOArray object / / fetches the value System.out.println of the first json sub-object in the sites corresponding array in the json object (jsonobj2.getJSONArray ("sites") .getJSONObject (0)) / / get results: {"name": "Google", "info": ["Android", "Google search", "Google Translation"]} System.out.println (jsonobj2.getJSONArray ("sites"). Get (0); System.out.println (jsonobj2.getJSONArray ("sites"). GetString (0)) / / take out the nested subarray value System.out.println (jsonobj2.getJSONArray ("sites") .getJSONObject (0) .getJSONArray ("info") corresponding to info under the first sites sub-object in the json object. / / get the result: ["Android", "Google search", "Google Translation"] / / extract the second value System.out.println (jsonobj2.getJSONArray ("sites") .getJSONObject (0) .getJSONArray ("info") .getString (1) from the nested subarray of info under the first json sub-object in the sites corresponding array in the json object. / / get the result: Google search / / fetches the value JSONArray array = jsonobj2.getJSONArray ("sites") in the sites corresponding array in the json object; getJsonArrayItem (array); / / fetches the nested subarray value JSONArray arr = jsonobj2.getJSONArray ("sites"). GetJSONObject (1). GetJSONArray ("info") corresponding to the info under the second json sub-object in the json object. GetJsonArrayItem (arr);} / * manually add objects to a JSONObject * / private static void writeStrToJSONObject () {JSONObject jsonObject = new JSONObject (); jsonObject.put ("name", "tom"); jsonObject.put ("age", 20); JSONArray jsonArray = new JSONArray (); JSONObject jsonArrayObject1 = new JSONObject (); jsonArrayObject1.put ("name", "alibaba") JsonArrayObject1.put ("info", "www.alibaba.com"); JSONObject jsonArrayObject2 = new JSONObject (); jsonArrayObject2.put ("name", "baidu"); jsonArrayObject2.put ("info", "www.baidu.com"); jsonArray.add (jsonArrayObject1); jsonArray.add (jsonArrayObject2); jsonObject.put ("sites", jsonArray); System.out.println (jsonObject) } / * convert the string to JSONArray * / private static void strToJsonArray () {String arrayStr = "[\ n" + "{\ n" + "\" name\ ":\" alibaba\ " \ n "+"\ "info\":\ "www.alibaba.com\"\ n "+"},\ n "+" {\ n "+"\ "name\":\ "baidu\" \ n "+"\ "info\":\ "www.baidu.com\"\ n "+"}\ n "+"] " JSONArray array = JSON.parseArray (arrayStr); System.out.println (array);} / * take out the value in JSONArray in turn * / private static void getJsonArrayItem (JSONArray array) {for (int item0; I)