简体   繁体   English

Java JSON /对象到数组

[英]Java JSON/object to array

I have a question about type casting. 我对类型转换有疑问。 I have the following JSON String: 我有以下JSON字符串:

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

I am parsing it to the following Map<String, Object>. 我将其解析为以下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 . 值很可能是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 : 但是为了获得更方便的访问权限,请看一下Jackson ,特别是其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: 当然,Jackson也可以绑定到常规Map,方法如下:

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. 但是由于强制转换以及无法优雅地处理null,访问Maps不太方便。

Maybe 也许

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

? You could also try casting this to a String[] . 您也可以尝试将其强制转换为String[]

Anyway, there are more civilized ways of parsing JSON, such as http://code.google.com/p/google-gson/ . 无论如何,还有更多文明的JSON解析方式,例如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 StaxMan是正确的,假设Java中的JSON数组的类型为List (以ArrayList作为实现),并假设JSON被反序列化,类似于

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". 此外, 有关基本JSON解析的svenson文档还描述了“ [b]默认情况下,数组将解析为java.util.List实例”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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