从Java中的JSON获取键值-JSON解析

我有一个json如下。我想从此jsonObject获取mobile_number

json:-

{"id": "ABCD","report": { "data": { "phone": { "mobile_number": 9876543210,"active": "Y","content": null } } } }

我正在这样做,并且效果很好,但是有人可以在没有所有密钥的情况下以其他任何方式帮助我。

JSONObject jsonObject = new JSONObject(json);
JSONObject report = getJSONObjectFromJson(jsonObject,"report");
JSONObject data = getJSONObjectFromJson(jsonObject,"data");
JSONObject phone = getJSONObjectFromJson(data,"phone");
long mobileNumber = getLongFromJson(phone,"mobile_number");

private Long getLongFromJson(JSONObject object,String key){
    return (object !=null && object.has(key)) ? object.getLong(key) : null;
}

private JSONObject getJSONObjectFromJson(JSONObject object,String key){
    return (object !=null && object.has(key)) ? object.getJSONObject(key) : null;
}
gukoule 回答:从Java中的JSON获取键值-JSON解析

我刚刚处理了类似的问题,并决定像这样使用JsonPath:

final DocumentContext jsonContext = JsonPath.parse(jsonString);
final Object read = jsonContext.read("$['report']['data']['phone']['mobile_number']");
,

您可以使用Jackson ObjectMapper。

        try {
            ObjectMapper mapper = new ObjectMapper();
            String jsonString = "{\"id\": \"ABCD\",\"report\": { \"data\": { \"phone\": { \"mobile_number\": 9876543210,\"active\": \"Y\",\"content\": null } } } }";
            JsonNode rootNode = mapper.readTree(jsonString);

            JsonNode mobileNumber = rootNode.path("report").path("data").path("phone").path("mobile_number");
            System.out.println("Mobile Number: " + mobileNumber.longValue());

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
,

所以有很多方法可以做到,但是一切最终都会导致遍历树。

所以总结所有方法,

sourceIndex
,
jsonObject.getJSONObject("x").getJSONObject("Y").getJSONObject("z");

另一种方法是利用 ObjectMapper

本文链接:https://www.f2er.com/3097092.html

大家都在问