使用嵌套属性反序列化JSON对象

时间:2020-09-23 06:13:38

标签: java json jackson annotations

我正在尝试使用属性反序列化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, 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在第1行,第25列,即内部地图的开始位置。

关于如何绘制内部地图的任何想法? 如果地图只有一层深,我可以获取正确的值。

{
   "operation_rand": 100
}

然后将上面的地图调整为Map<String, Integer>

3 个答案:

答案 0 :(得分:2)

您需要一个对象表示形式来获取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);

答案 1 :(得分:0)

100不是Map

也许使用Map<String,Object>而不是Map<String, Map<String, Integer>>

通过instanceof Integerinstanceof Map确定类型。

答案 2 :(得分:0)

您只需要像这样简化类:

public class Operation {
    @JsonProperty("operation_rand")
    private Map operationDetails;
    
    public Map getOperation() {
        return operationDetails;
    }
}