F
F
fsfsfs322020-09-14 07:55:13
Java
fsfsfs32, 2020-09-14 07:55:13

How to get element from json array in java associatively (vk longpool)?

When I contact the VKontakte server to get data for a long pool request, I get the following response:

Array
(
    [response] => Array
        (
            [key] => 3frf4b6e17478cеf5c463c4f14a5afcd93208412a
            [server] => https://lp.vk.com/wh123264621
            [ts] => 15
        )

)


How to get all these parameters in java from org.json?

My code:
import org.json.*;

public class test123 {
    public static void main(String args[]){
        String json = "{"response":{"key":"12312","server":"12312312","ts":"231"}}"; // (with `\` before ` " ` )

        JSONObject o = new JSONObject(json);
        JSONArray a = o.getJSONArray("response");
        String out = (String) a.get("key");
        System.out.println(out);
    }
}


Well, of course, this doesn't work because a.get needs an int. how to make it ```associative```

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Lupolov, 2020-09-14
@johnny_jla

If you need to get not the whole object, but some nodes:

String json = "{"response":{"key":"12312","server":"12312312","ts":"231"}}";
ObjectMapper mapper = new ObjectMapper();
 JsonNode jsonNode = mapper.readTree(json);
 String key = jsonNode.get("key").asText();

If you need to map onto an object, then:
ObjectMapper mapper = new ObjectMapper()
YourObject obj = mapper.readValue(jsonString, YourObject.class);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question