2 回答
TA贡献1793条经验 获得超6个赞
是的,您的伪代码是正确的方法。首先使用 Jackson 反序列化您的 JSON 字符串(找到合适的“模型”,例如nextTo
可以映射到 a Map<Integer, List<Integer>>
),然后实现您的伪代码。
TA贡献1797条经验 获得超6个赞
使用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 {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
//json string
String stringToParse="{\"Regions\" : [{\"regionId\" : 5,\"name\" : \"South Korea\"},{\"regionId\" : 6,\"name\" : \"North Korea\"},{ }],\"nextTo\" : { \"5\" : [6], \"6\" : [5]}}";
try {
//convert to json object
JSONObject json = (JSONObject) parser.parse(stringToParse);
System.out.println(checkNextTo(json));
} catch (ParseException e) {
e.printStackTrace();
}
}
public static boolean checkNextTo(JSONObject json) {
//regions array
JSONArray regionArr=(JSONArray) json.get("Regions");
// Find the id of region1 in the "region" part of the JSON
long regionId1=(Long) ((JSONObject) regionArr.get(0)).get("regionId");
// Find the id of region2 in the "region" part of the JSON
long regionId2=(Long) ((JSONObject) regionArr.get(1)).get("regionId");
JSONObject nextTo=(JSONObject) json.get("nextTo");
Long nextToReg1=(Long) ((JSONArray) nextTo.get(String.valueOf(regionId1))).get(0);
Long nextToReg2=(Long) ((JSONArray) nextTo.get(String.valueOf(regionId2))).get(0);
// Check region1's nextTo regions in the "nextTo" section ofJSON
// If region2 id is in region1 id's nextTo {
//return True
// Else
return regionId1==nextToReg2 || regionId2==nextToReg1;
}
}
添加回答
举报