将字符串数组作为字段的Java对象转换为JSONObject
我有一个数据模型,它是一个字符串[]。当我尝试使用以下代码将模型转换为JSONObject时:将字符串数组作为字段的Java对象转换为JSONObject,java,json,Java,Json,我有一个数据模型,它是一个字符串[]。当我尝试使用以下代码将模型转换为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[
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);
字符串[]未正确转换。使用上面的代码,我希望JSONObject如下所示:
{
id: 123,
Q1: This is Question 1,
Q2: [Part 1, Part 2]
}
{
id: 123,
Q1: This is Question 1,
Q2: [{"bytes":[{},{},{},{}],"empty":false},{"bytes":[{},{},{},{}],"empty":false}]
}
但我得到的JSONObject是这样的:
{
id: 123,
Q1: This is Question 1,
Q2: [Part 1, Part 2]
}
{
id: 123,
Q1: This is Question 1,
Q2: [{"bytes":[{},{},{},{}],"empty":false},{"bytes":[{},{},{},{}],"empty":false}]
}
有没有办法解决这个问题?提前感谢。将条目逐步放入JSONObject并 首先将数组转换为ArrayList 您可以使用它,因为它非常高效:
class CheckList {
private String id = "123";
private String Q1 = "This is Question 1";
private String[] Q2 = {"Part 1", "Part 2"};
}
final String jsonObject = new Gson().toJson(new CheckList());
System.out.print(jsonObject);
输出:
{
"id": "123",
"Q1": "This is Question 1",
"Q2": [
"Part 1",
"Part 2"
]
}
您可能需要在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));
}
}
用于Jackson和文档的maven central URL。嘿,感谢您的解决方案。我正在寻找一种可以直接将模型转换为json的解决方案。我的实际清单模型有20多个字段,所以您的解决方案不适合我的用例。