在Java中使用链接键获取嵌套JSON值
我有一个JSON对象,如下所示。在Java中,是否可以使用链式键从一个get调用中获取嵌套值?例如:在Java中使用链接键获取嵌套JSON值,java,json,Java,Json,我有一个JSON对象,如下所示。在Java中,是否可以使用链式键从一个get调用中获取嵌套值?例如: String fname = jsonObj.get("shipmentlocation.personName.first") { "shipmentLocation": { "personName": { "first": “firstName”, "generationalSuffix": "string",
String fname = jsonObj.get("shipmentlocation.personName.first")
{
"shipmentLocation": {
"personName": {
"first": “firstName”,
"generationalSuffix": "string",
"last": "string",
"middle": "string",
"preferredFirst": "string",
"prefix": "string",
"professionalSuffixes": [
"string"
]
}
},
"trackingNumber": "string"
}
这对我使用JSONObject类不起作用,所以我很好奇是否有其他方法可以做到这一点。谢谢 使用您提供的json,您需要经历几个级别
String firstName = jsonObj.getJSONObject("shipmentLocation").getJSONObject("personName").getString("first");
请注意,如果您在json节点或其子节点中查找的任何字段可能不存在,则可能会遇到上面提到的一些空指针问题。在这种情况下,更明智的做法可能是查看javaOptional
s,或者在每个步骤中使用空检查,如下所示:
String firstName = null;
JSONObject shipmentLocation = jsonObj.getJSONObject("shipmentLocation");
if (shipmentLocation != null) {
JSONObject personName = shipmentLocation.getJSONObject("personName");
if (personName != null) {
firstName = personName.getString("first");
}
}
if (firstName != null) {
// do something with the first name
}
使用这个库-json-simple-1.1.jar(链接-)
猜测这取决于您使用的JSON库,但可能不适用于普通JSON库。您正在寻找的是一个JSONPath库,例如,我认为这会起作用。谢谢大家!<代码>发货位置不是数组。
String name = "";
JSONObject jsonObject = (JSONObject) new JSONParser().parse(new FileReader("Path to your file"));
JSONObject jsonObject2 = jsonObject.get("shipmentLocation");
JSONObject jsonObject3 = jsonObject2.get("personName");
name = jsonObject3.get("first").toString();