我有一个数据模型,它是一个 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));
}
}
关于java - 将字符串数组作为字段的 Java 对象转换为 JSONObject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42308088/