I found some code for my question but that dose not work in my case
I have a JSON say
{
"A":{
"B":{
"STATUS":"ok",
"TYPE":"Unknown",
"NAME":"UnchangedECN"
}
}
}
How do I fetch the value of Status Type and Name?
Here is what I've tried
long A ;
String STATUS = "";
String TYPE = "";
String NAME = "";
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(new File("BOM.json"));
// Get id
A = root.path("A").asLong();
System.out.println("A : " + A);
// Get Name
JsonNode nameNode = root.path("A");
if (nameNode.isMissingNode()) {
// if "name" node is missing
} else {
STATUS = nameNode.path("STATUS").asText();
// missing node, just return empty string
TYPE = nameNode.path("TYPE").asText();
NAME = nameNode.path("NAME").asText();
System.out.println("STATUS : " + STATUS);
System.out.println("TYPE : " + TYPE);
System.out.println("NAME : " + NAME);
}
You can use a JSON library to make it easier to deal with. For example, using the org.json
maven dependency:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
I used the following code to "unwrap" the desired JSONObject:
@Test
public void foo() {
String jsonString = "{'A':{'B':{'STATUS':'ok','TYPE':'Unknown','NAME':'UnchangedECN'}}}";
JSONObject object = new JSONObject(jsonString);
JSONObject a = object.getJSONObject("A");
JSONObject b = a.getJSONObject("B");
System.out.println(b.getString("STATUS"));
System.out.println(b.getString("TYPE"));
System.out.println(b.getString("NAME"));
}
Which spit out the following output:
ok
Unknown
UnchangedECN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.