[英]Deserialize JSON Object with nested attributes
我正在尝试使用属性反序列化 json object
其中第一个键名未知,而内部 map 始终包含名为“key1”和“key2”的两个属性。
{
"operation_rand":
{
"key1": 1005,
"key2": 5
}
}
我有代码:
操作.java
public class Operation {
private Map<String, Map<String, Integer>> operationDetails = new HashMap<>();
@JsonAnyGetter
public Map<String, Map<String, Integer>> getOperation() {
return operationDetails;
}
}
主要的
ObjectMapper mapper = new ObjectMapper();
Operation op = mapper.readValue(jsonData, Operation.class);
Map<String, Map<String, Integer>> oDetails = address.getOperation();
但是我收到错误: Can not deserialize instance of java.lang.String out of START_OBJECT token
,这是内部 map 开始的地方。
关于我如何 map 内部 map 的任何想法? 如果 map 只有一层深,我可以获取正确的值。
{
"operation_rand": 100
}
并将上面的地图调整为Map<String, Integer>
对于预期的 JSON 和 Gson 依赖项,您需要一个 Object 表示
Class 为 Object
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName("operation_rand")
public class OperationRand{
@JsonProperty("key1")
private int key1;
@JsonProperty("key2")
private int key2;
public int getKey1() {
return key1;
}
public void setKey1(int key1) {
this.key1 = key1;
}
public int getKey2() {
return key2;
}
public void setKey2(int key2) {
this.key2 = key2;
}
public OperationRand(int key1, int key2) {
this.key1 = key1;
this.key2 = key2;
}
@Override
public String toString() {
return "OperationRand{" +
"key1=" + key1 +
", key2=" + key2 +
'}';
}
}
Gson 来自谷歌
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
然后,
String json ="{\n" +
" \"operation_rand\":\n" +
" {\n" +
" \"key1\": 1005, \n" +
" \"key2\": 5\n" +
" }\n" +
"}";
Gson gson = new Gson();
OperationRand res = gson.fromJson(json, OperationRand.class);
System.out.println(res);
[编辑]对于 Changing operation_rand 我会使用 object 作为不变的字段
import lombok.*;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Key {
int key1;
int key2;
}
在主要
Gson gson = new Gson();
Map<String,Key> rest = gson.fromJson(json,HashMap.class);
System.out.println(rest);
100 不是 Map<String, Integer>。
也许使用Map<String,Object>
而不是Map<String, Map<String, Integer>>
。
通过instanceof Integer
、 instanceof Map
来判断类型。
您只需要像这样简化 class :
public class Operation {
@JsonProperty("operation_rand")
private Map operationDetails;
public Map getOperation() {
return operationDetails;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.