首先,您指定的输入永远不能反序列化为数组或集合,因为它不是一个。键值对的 json 集合看起来像这样
[
{"foo": "bar"},
{"key": true},
{"otherKey": 10}
]
如果你像这样创建类,它可以反序列化为Wrappers 的集合
public class Wrapper<T> {
private String key;
private T value;
@JsonAnySetter
public void set(String key, Object value) {
this.key = key;
this.value = (T)value;
}
public String toString() { // just for nice printing
return key + "=" + value.toString();
}
}
然后你必须告诉 Jackson 将托管反序列化 json 的集合的通用类型是什么:
public static void main(String[] args)
{
String str = "[ {\"foo\": \"bar\"}, {\"key\": true}, {\"otherKey\": 10} ]";
try (InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8"))) {
ObjectMapper objectMapper = new ObjectMapper();
JavaType listWrappersType = objectMapper.getTypeFactory()
.constructCollectionType(List.class, Wrapper.class);
List<Wrapper> list = objectMapper.readValue(is, listWrappersType);
System.out.println(list);
} catch (Exception e) {
e.printStackTrace();
}
}
输出:
[foo=bar, key=true, otherKey=10]
如果您只想加载键值对而不担心值的类型,那么使用 Jackson 您可以将其全部加载到 Map<String, ?>
public static void main(String[] args)
{
String str = "{ \"foo\": \"bar\", \"key\": true, \"otherKey\": 10 }";
try (InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8"))) {
Map<String, ?> map = new ObjectMapper().readValue(is, Map.class);
// print map contents
System.out.println(map);
// print type of map values
System.out.print(entry.getKey() + "=" + entry.getValue().getClass()+ ", "));
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
输出
{foo=bar, key=true, otherKey=10}
foo=class java.lang.String, key=class java.lang.Boolean, otherKey=class java.lang.Integer,