java - 将字符串数组作为字段的 Java 对象转换为 JSONObject

标签 java json

我有一个数据模型,它是一个 String[]。当我尝试使用以下代码将模型转换为 JSONObject 时:

public class CheckList {
    private String id = "123";
    private String Q1 = "This is Question 1";
    private String[] Q2 = ["Part 1", Part 2"];

    public CheckList (String, id, String Q1, String[] Q2){
       ...
    }
}

CheckList checklist = new Checklist("123", "This is Question 1", ["Part 1", "Part 2"]

JSONObject test = new JSONObject(checklist);

String[] 未正确转换。通过上面的代码,我想要一个如下所示的 JSONObject:

{
  id: 123,
  Q1: This is Question 1,
  Q2: [Part 1, Part 2]
}

但我得到的 JSONObject 像这样:

{
  id: 123,
  Q1: This is Question 1,
  Q2: [{"bytes":[{},{},{},{}],"empty":false},{"bytes":[{},{},{},{}],"empty":false}]
}

有什么办法可以解决这个问题吗?提前致谢。

最佳答案

您可能需要在 CheckList 类中使用 JsonArray 来反序列化数组。但是,如果您的实现允许,您可以使用 Jackson 将对象转换为 json,它很容易使用,并且不需要像 JsonArray 这样的位来转换对象。下面是一个例子:

public class CheckList {
    private String id = "123";
    private String Q1 = "This is Question 1";
    private String[] Q2;

    public CheckList (String id, String Q1, String[] Q2){
       this.id = id;
       this.Q1 = Q1;
       this.Q2 = Q2;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getQ1() {
        return Q1;
    }

    public void setQ1(String q1) {
        Q1 = q1;
    }

    public String[] getQ2() {
        return Q2;
    }

    public void setQ2(String[] q2) {
        Q2 = q2;
    }

    public static void main(String[] args) throws Exception{
        CheckList checklist = new CheckList("123", "This is Question 1", new String[]{"Part 1", "Part 2"});
        ObjectMapper objectMaapper = new ObjectMapper();
        System.out.println(objectMaapper.writeValueAsString(checklist));

    }
}

Here's Jackson 的 Maven 中心 URL 和 here's文档。

关于java - 将字符串数组作为字段的 Java 对象转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42308088/

相关文章:

java - 使用Jackson解析和未命名数组

java - ConstraintLayout 设计器渲染异常

json - 从 Json 中提取数据以进行 ng-bootstrap typeahead

javascript - 无法将 JSON 值 append 到模式中

javascript - AngularJS 和 Web API 中请求的资源上不存在 'Access-Control-Allow-Origin' header

Java 菜单驱动编程和循环

java - 如何在另一个线程JAVA中访问 volatile 变量

java - 为什么 System.nanoTime() 比 System.currentTimeMillis() 慢(在性能上)?

javascript - 如何重新格式化这个简单的 JSON,使其不会捕获 "Circular structure to JSON"异常?

mysql - 从laravel 4中的json数组获取元素