猿问

检查 Java 中的“nextTo”区域

“NextTo”表示哪些区域。卡在解析上。



蝴蝶刀刀
浏览 108回答 2
2回答

摇曳的蔷薇

是的,您的伪代码是正确的方法。首先使用 Jackson 反序列化您的 JSON 字符串(找到合适的“模型”,例如nextTo可以映射到 a&nbsp;Map<Integer, List<Integer>>),然后实现您的伪代码。

互换的青春

使用org.json反序列化对象,import org.json.simple.JSONArray;import org.json.simple.JSONObject;import org.json.simple.parser.JSONParser;import org.json.simple.parser.ParseException;public class DesrialiseJSON {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; JSONParser parser = new JSONParser();&nbsp; &nbsp; &nbsp; &nbsp; //json string&nbsp; &nbsp; &nbsp; &nbsp; String stringToParse="{\"Regions\" : [{\"regionId\" : 5,\"name\" : \"South Korea\"},{\"regionId\" : 6,\"name\" : \"North Korea\"},{ }],\"nextTo\" : { \"5\" : [6], \"6\" : [5]}}";&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //convert to json object&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JSONObject json = (JSONObject) parser.parse(stringToParse);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(checkNextTo(json));&nbsp; &nbsp; &nbsp; &nbsp; } catch (ParseException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public static boolean checkNextTo(JSONObject json) {&nbsp; &nbsp; &nbsp; &nbsp; //regions array&nbsp; &nbsp; &nbsp; &nbsp; JSONArray regionArr=(JSONArray) json.get("Regions");&nbsp; &nbsp; &nbsp; &nbsp; // Find the id of region1 in the "region" part of the JSON&nbsp; &nbsp; &nbsp; &nbsp; long regionId1=(Long) ((JSONObject) regionArr.get(0)).get("regionId");&nbsp; &nbsp; &nbsp; &nbsp; // Find the id of region2 in the "region" part of the JSON&nbsp; &nbsp; &nbsp; &nbsp; long regionId2=(Long) ((JSONObject) regionArr.get(1)).get("regionId");&nbsp; &nbsp; &nbsp; &nbsp; JSONObject nextTo=(JSONObject) json.get("nextTo");&nbsp; &nbsp; &nbsp; &nbsp; Long nextToReg1=(Long) ((JSONArray) nextTo.get(String.valueOf(regionId1))).get(0);&nbsp; &nbsp; &nbsp; &nbsp; Long nextToReg2=(Long) ((JSONArray) nextTo.get(String.valueOf(regionId2))).get(0);&nbsp; &nbsp; &nbsp; &nbsp; // Check region1's nextTo regions in the "nextTo" section ofJSON&nbsp; &nbsp; &nbsp; &nbsp; // If region2 id is in region1 id's nextTo {&nbsp; &nbsp; &nbsp; &nbsp; //return True&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // Else&nbsp; &nbsp; &nbsp; &nbsp; return regionId1==nextToReg2 || regionId2==nextToReg1;&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答