有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为JSON创建POJO,其中子节点是动态的

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

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

值节点内的节点可以根据应用程序的状态增加或减少。我正在尝试为上述响应创建pojo,以便获得值列表。有人能帮我为同样的东西制作POJO吗


共 (1) 个答案

  1. # 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);
          }
      
      }