2017-02-17 73 views
0

我有一个数据模型,那是一个String []。当我尝试使用以下代码将模型转换为JSONObject:将字符串数组作为字段转换为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}] 
} 

有没有什么办法来解决这个问题?提前致谢。

回答

0

您可以使用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" 
    ] 
} 
0

将条目逐步放入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)); 
+0

嘿,谢谢你的解决方案。我正在寻找更多的解决方案,将直接将模型转换为json。我的实际清单模型有20个字段,所以你的解决方案不适合我的用例。 – SL07

1

您可能需要使用JsonArrayCheckList类反序列化数组。但是,如果您的实现允许,则可以使用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)); 

    } 
} 

Here's行家杰克逊和here's文档中心URL。