需要帮助构建JSONObject java

时间:2014-03-06 19:12:40

标签: java json

我正在尝试动态地在java中构建以下json对象,例如,如果WARN对象不存在,添加它或任何其他对象,然后向子数组添加新的标签消息对象。

这是我正在尝试动态构建的示例。

{
  "warnings" : [
    {
      "WARN" : [
        {
          "label" : "Label Goes Here",
          "message" : "Message Goes Here"
        },
        {
          "label" : "Label Goes Here2",
          "message" : "Message Goes Here2"
        }
      ],"title" : "Please review the following warnings"
    },
    {
      "NOTIFICATION" : [
        {
          "label" : "Label Goes Here3",
          "message" : "Message Goes Here3"
        },
        {
          "label" : "Label Goes Here4",
          "message" : "Message Goes Here4"
        }
      ],"title" : "Please review the following warnings"
    }
  ]
}

这就是我尝试过的。

public class Warning {
    warningTypes = new JSONObject();
}

private JSONObject warningTypes;    

public Warning() {

public Warning(WarningType warningType, String label, String message) {
        this.warningType = warningType;
        this.label = label;
        this.message = message;
    }

    public void add(WarningType warningType, String label, String message) {
        addToJSON(warningType, new JSONObject("label",label,"message",message));        
    }

    private void addToJSON(WarningType warningType, JSONObject jsonObj) {       
        if(warningTypes.has(warningType.name())) {
            JSONArray array = warningTypes.getJSONArray(warningType.name());   
            array.put(jsonObj);
        } else {

            warningTypes.put(warningType.name(), new JSONArray(jsonObj));
        }
    }

    public JSONObject toJSON() {
        return new JSONObject("warnings", new JSONArray(warningTypes));
    }

}

然而,这是我的结果,你可以看到是不正确的。我无法将标题添加到我的warningTypes正在进入单个对象的事实中。

{
  "warnings" : [
    {
      "WARN" : [
        {
          "label" : "Label Goes Here",
          "message" : "Message Goes Here"
        },
        {
          "label" : "Label Goes Here2",
          "message" : "Message Goes Here2"
        }
      ],
      "NOTIFICATION" : [
        {
          "label" : "Label Goes Here3",
          "message" : "Message Goes Here3"
        },
        {
          "label" : "Label Goes Here4",
          "message" : "Message Goes Here4"
        }
      ]
    }
  ]
}

我无法弄清楚如何动态构建此对象,任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

您尝试创建的JSON没有相同的密钥。以下代码将为您提供所需的输出。必要时将零件重构为方法。

代码:

public static class Message {
        private String label;
        private String message;

        public String getMessage() {
            return message;
        }

        public String getLabel() {
            return label;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public void setLabel(String label) {
            this.label = label;
        }
    }

    public static enum WarningType {
        WARN, NOTIFICATION
    }

    public static class Warning {

        WarningType type;
        List<Message> messages;
        String title;

        public WarningType getType() {
            return type;
        }

        public void setType(WarningType type) {
            this.type = type;
        }

        public void setMessages(List<Message> messages) {
            this.messages = messages;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public List<Message> getMessages() {
            return messages;
        }

        public String getTitle() {
            return title;
        }
    }

    public static class Warnings {
        List<Map<String, Object>> warnings;

        public List<Map<String, Object>> getWarnings() {
            return warnings;
        }

        public void setWarnings(List<Map<String, Object>> warnings) {
            this.warnings = warnings;
        }

        public void setWarningsInMap(List<Warning> warningList) {
            warnings = new ArrayList<>();
            for(Warning each : warningList) {
                Map<String, Object> m = new LinkedHashMap<>();
                m.put(each.getType().name(), each.getMessages());
                m.put("title", each.getTitle());
                warnings.add(m);
            }
        }
    }

    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
        List<Warning> warningList = new ArrayList<>();

        Warning warn = new Warning();
        warn.setType(WarningType.WARN);

        List<Message> warnMessages = new ArrayList<>();

        Message m = new Message();
        m.setLabel("Label Goes Here");
        m.setMessage("Message Goes Here");
        warnMessages.add(m);

        m = new Message();
        m.setLabel("Label Goes Here2");
        m.setMessage("Message Goes Here2");
        warnMessages.add(m);

        warn.setMessages(warnMessages);

        warn.setTitle("Please review the following warnings");

        warningList.add(warn);

        Warning notification = new Warning();
        notification.setType(WarningType.NOTIFICATION);

        List<Message> notificationMessages = new ArrayList<>();

        m = new Message();
        m.setLabel("Label Goes Here3");
        m.setMessage("Message Goes Here3");
        notificationMessages.add(m);

        m = new Message();
        m.setLabel("Label Goes Here4");
        m.setMessage("Message Goes Here4");
        notificationMessages.add(m);

        notification.setMessages(notificationMessages);

        notification.setTitle("Please review the following warnings");

        warningList.add(notification);

        Warnings w = new Warnings();
        w.setWarningsInMap(warningList);

        String s = new ObjectMapper().defaultPrettyPrintingWriter().writeValueAsString(w);
        System.out.println(s);
    }

输出:

{
  "warnings" : [ {
    "WARN" : [ {
      "message" : "Message Goes Here",
      "label" : "Label Goes Here"
    }, {
      "message" : "Message Goes Here2",
      "label" : "Label Goes Here2"
    } ],
    "title" : "Please review the following warnings"
  }, {
    "NOTIFICATION" : [ {
      "message" : "Message Goes Here3",
      "label" : "Label Goes Here3"
    }, {
      "message" : "Message Goes Here4",
      "label" : "Label Goes Here4"
    } ],
    "title" : "Please review the following warnings"
  } ]
}

答案 1 :(得分:0)

以下是link的综合指南。

如果您想减少工作量,可以使用 Google GSON 将POJO序列化为JSON对象。 GSON可以序列化POJO,数组,列表,地图和其他集合,并自动区分数字和字符串。这允许更好的面向对象设计,并允许您将序列化推迟到GSON的JSON对象。您不必担心动态修改JSON,只需动态修改POJO即可。假设你有一些对象:

public class Warnings {
  @SerializedName("WARN")
  private Warn[] warns;
  @SerializedName("NOTIFICATION")
  private Notification[] notifications;

  public WARN[] getWARN(){...}

  public void setWarn(WARN[] warns){...}
  ...
}

public class Warn {
  private String message;
  private String label;
  ... // setters & getters
}

public class Notification {
  private String message;
  private String label;
  ... // setters & getters
}

你明白了

然后你可以序列化它:

Warnings someWarnings = new Warnings();
// Populate warnings
Gson gson = new Gson();
// Serialize
String jsonString = gson.toJson(someWarnings);
// Deserialize
Warnings sameWarinings = gson.fromJson(jsonString);