如何解决使用嵌套属性反序列化JSON对象
我正在尝试使用属性反序列化json对象
其中第一个键名未知,而内部映射始终包含两个名为“ key1”和“ key2”的属性。
{
"operation_rand":
{
"key1": 1005,"key2": 5
}
}
我有代码:
Operation.java
public class Operation {
private Map<String,Map<String,Integer>> operationDetails = new HashMap<>();
@JsonAnyGetter
public Map<String,Integer>> getOperation() {
return operationDetails;
}
}
主要
ObjectMapper mapper = new ObjectMapper();
Operation op = mapper.readValue(jsonData,Operation.class);
Map<String,Integer>> oDetails = address.getOperation();
但是我得到了错误:
Can not deserialize instance of java.lang.String out of START_OBJECT token
在第1行,第25列,即内部地图的开始位置。
关于如何绘制内部地图的任何想法? 如果地图只有一层深,我可以获取正确的值。
{
"operation_rand": 100
}
然后将上面的地图调整为Map<String,Integer>
解决方法
您需要一个对象表示形式来获取Gson依赖项所需的JSON
对象的类
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来自Google
<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);
[EDIT]更改操作_rand 我会将对象用于不变的字段
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
也许使用Map<String,Object>
而不是Map<String,Map<String,Integer>>
。
通过instanceof Integer
,instanceof Map
确定类型。
您只需要像这样简化类:
public class Operation {
@JsonProperty("operation_rand")
private Map operationDetails;
public Map getOperation() {
return operationDetails;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。