为子节点是动态的JSON创建POJO

时间:2018-05-15 09:41:46

标签: java json rest

我有一个看起来像这样的JSON文件。我将收到此JSON作为API的响应:

{
    "success": true,
    "message": "SUCCESS",
    "value": {
        "APP": {
            "option1": false,
            "option2": false
        },
        "DESKTOP": {
            "multiValued": true,
            "lob": true
        },
        "TestSomeLob": {
            "multiValued": true,
            "lob": true
        }
    }
}

值节点内的节点可以根据应用程序的状态增加或减少。我正在尝试为上面提到的响应创建pojo,以便我可以获取值列表。任何人都可以帮我创建同样的pojos吗?

1 个答案:

答案 0 :(得分:1)

使用

的组合
  1. jsonanygetter(http://tutorials.jenkov.com/java-json/jackson-annotations.html#jsonanygetter
  2. jsonanysetter(http://tutorials.jenkov.com/java-json/jackson-annotations.html#jsonanysetter
  3. jsoncreator(http://tutorials.jenkov.com/java-json/jackson-annotations.html#jsoncreator

    public class POJONAME_TO_BE_REPLACED{
    
        // Two mandatory properties
        protected final boolean success;
        protected final String message;
    
        // Other flexible properties
        protected Map<String,Object> otherProps = new HashMap<String,Object>();
    
        @JsonCreator
        public POJONAME_TO_BE_REPLACED(@JsonProperty("success") boolean success, @JsonProperty("message") String message)
        {
            this.success = success;
            this.message = message;
        }
    
        public boolean getSuccess() { return success; }
        public String getMessage() { return message; }
    
        public Object get(String propName) {
            return otherProps.get(propName);
        }
    
        @JsonAnyGetter
        public Map<String,Object> any() {
            return otherProps;
        }
    
        @JsonAnySetter
        public void set(String propName, Object value) {
            otherProps.put(propName, value);
        }
    
    }