[英]Convert Java Object with String Array as a Field to JSONObject
我有一個數據模型,它是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}]
}
有什么辦法可以解決此問題? 提前致謝。
您可能需要使用JsonArray
內部CheckList
類反序列化數組。 但是,如果您的實現允許,則可以使用Jackson
轉換對象inso 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));
}
}
將條目逐步放入JSONObject
然后首先將數組轉換為ArrayList<String>
。
ArrayList<String> list = new ArrayList<String>();
list.add("Part 1");
list.add("Part 2");
JSONObject test = new JSONObject();
test.put("id", 123);
test.put("Q1","This is Question 1");
test.put("Q2", new JSONArray(list));
您可以使用Gson,它是如此高效:
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"
]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.