我有这样的 JSON 数据:
{
"foo": "bar",
"key": true,
"otherKey": 10
}
键是字符串,值是原始类型(int、float、double、long 等)或字符串。我想要一个简单的、无类型转换的包装器,用于上述每一个。
这是我的包装类:
public final class Wrapper<T> {
private String key;
private T value;
}
如果我在要反序列化的对象中指定 Wrapper[] wrappedValues
,我可以(使用 Jackson 或 GSON)将映射反序列化为包装器列表吗?
感谢您的任何回复!
最佳答案
首先,您指定的输入永远不能反序列化为数组或集合,因为它不是一个。键值对的 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,
关于java - 如何在 JSON 中存储键值对以在 Java 中反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39339175/