简体   繁体   中英

Java JSON/object to array

I have a question about type casting. I have the following JSON String:

{"server":"clients","method":"whoIs","arguments":["hello"]}

I am parsing it to the following Map<String, Object>.

{arguments=[hello], method=whoIs, server=clients}

It is now possible to do the following:

request.get("arguments");

This works fine. But I need to get the array that is stored in the arguments. How can I accomplish this? I tried (for example) the following:

System.out.println(request.get("arguments")[0]);

But of course this didn't work..

How would this be possible?

Most likely, value is a java.util.List . So you would access it like:

System.out.println(((List<?>) request.get("arguments")).get(0));

But for more convenient access, perhaps have a look at Jackson , and specifically its Tree Model :

JsonNode root = new ObjectMapper().readTree(source);
System.out.println(root.get("arguments").get(0));

Jackson can of course bind to a regular Map too, which would be done like:

Map<?,?> map = new ObjectMapper().readValue(source, Map.class);

But accessing Maps is a bit less convenient due to casts, and inability to gracefully handle nulls.

Maybe

 System.out.println( ((Object[]) request.get("arguments")) [0]);

? You could also try casting this to a String[] .

Anyway, there are more civilized ways of parsing JSON, such as http://code.google.com/p/google-gson/ .

StaxMan is correct that the type of the JSON array in Java is List (with ArrayList as implementation), assuming that the JSON is deserialized similar to

Map<String, Object> map = JSONParser.defaultJSONParser().parse(Map.class, jsonInput);

It is easy to determine such things by simply inspecting the types.

Map<String, Object> map = JSONParser.defaultJSONParser().parse(Map.class, jsonInput);
System.out.println(map);

for (String key : map.keySet())
{
  Object value = map.get(key);
  System.out.printf("%s=%s (type:%s)\n", key, value, value.getClass());
}

Output:

{arguments=[hello], method=whoIs, server=clients}
arguments=[hello] (type:class java.util.ArrayList)
method=whoIs (type:class java.lang.String)
server=clients (type:class java.lang.String)

Also, the svenson documentation on basic JSON parsing describes that "[b]y default, arrays will be parsed into java.util.List instances".

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