从 Java 对象到 JsonObject,嵌套问题 类

From Java object to JsonObject, problem with nested classes

我正在做一个 RESTful API 项目,我正在使用 JAVA 来完成端点创建,因为我工作的环境是 IBM Domino数据库。我正在使用 org.json jar 创建对象并提供所有响应,但现在我将修改项目,直接使用 Java classes,因为它变得越来越大... 顺便说一句,我对嵌套 Java 对象有疑问。

基本上,我在另一个 class 中实例化了 classes LabelValue、Content 和 ResultsBlock,它设置了所有必需的字段,并生成一个调用其构造函数和新对象的 JSONObject。当我这样做时,我有一个空指针异常,因此系统不提供任何响应。 我认为问题在于嵌套内容对象在 class 结果块中的声明。但我不知道我该如何处理这种情况。你能帮助我吗? 当我使用更简单的 classes 时,属性是通用数据类型,当我创建类型为 Content 的 ArrayList 时,我没有问题,一切正常。

提前致谢!

p.s。我无法使用 gson 库,因为它会导致 IBM Domino 服务器出现 java 策略问题。

public class LabelValue implements java.io.Serializable{
private String label;
private String value;

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

public void setValue(String value) {
    this.value = value;
};
}

public class Content implements java.io.Serializable{
private String title;
private String description;
private ArrayList <LabelValue> totals;


public void setTotals(ArrayList<LabelValue> totals) {
    this.totals = totals;
}

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

public void setDescription(String description) {
    this.description = description;
}}

public class ResultsBlock implements java.io.Serializable{
private String type;
private Content content;

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

public void setContent(Content content) {
    this.content = content;
}}

in the main  :
{
Content content = new Content();
content.setTitle("title");
content.setDescription("description");
content.setTotals(label);

ResultsBlock result = new ResultsBlock ();
result.setContent(content);
result.setType("result");

return new JSONObject(result);}

这是 blockResult 的预期输出 class:

"blocks":
{
  "type": "result",
  "content": {
    "title": "title",
    "description": "description",
    "totals": [
      {
        "label": "label",
        "value": value
      }
    ]
 }
  }

如果我没看错你需要什么,如果你不能使用 GSON,我建议你使用 Jackson

我尝试使用您提供的代码进行测试,在将所有 get 方法添加到您的 POJO 后 类,我实现了这个示例:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MainClass {

    public static void main(String[] args) throws JsonProcessingException {     

        Content content = new Content();
        content.setTitle("title");
        content.setDescription("description");

        ResultsBlock result = new ResultsBlock ();
        result.setContent(content);
        result.setType("result");

        //  JSONObject(result);
        ObjectMapper mapper = new ObjectMapper(); 

        String jsonString = mapper.writeValueAsString(result);

        System.out.println(jsonString);
    }


}

它打印出以下内容:

{
    "type": "result",
    "content": {
        "title": "title",
        "description": "description",
        "totals": null
    }
}

现在您可以随心所欲地访问您的JSON。 当然,为了简单起见,我没有考虑所有字段。

希望对您有所帮助。