简体   繁体   中英

Need to get id value from json array in java

JSONObject test = get_details();

Here is my input:

   test = {"users": [{"id": 1, "address": "CA"}]}
   System.out.println("test : " + test);

   users = test.get("users")
   System.out.println("users : " + users);

output:

test : {"users": [{"id": 1, "address": "CA"}]}
users : [{"id": 1, "address": "CA"}]

I want to get the id value from users as below:

1

How can I get it?

Users is an array. So you can try:

users[0].id

You can use JSONObject and parse your JSON String like this:

String jsonMessage='{"users": [{"id": 1, "address": "CA"}]}';
Scanner scanner = new Scanner(jsonMessage);
while (scanner.hasNextLine()) {
     JsonObject jsonObject = Json.createReader(new StringReader(scanner.nextLine())).readObject();
     System.out.println("the id is :"+jsonObject.getInt("id"));
}

And you can manage the jsonObject.getInt("id") like you want.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM