如何将String数组转换为Json数组

时间:2016-02-07 07:00:25

标签: java arrays

我有一个像string []句子一样的字符串数组,它包含每个索引中的一个句子,如This is the first message中的sentences[0]This is the second message中的sentences[1]等等。我将用于发送信息的java代码发送到服务器进行情感分析是这样的:

OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());  
        out.write(
                "[ " +
                "\"Can't wait for the movie\"," +
                "\"Countdown! Only ten days remaining!\" " +
                "]");
        out.flush();
        out.close();

如何用字符串数组替换代码中的上述文本,因为它的长度为n?

2 个答案:

答案 0 :(得分:8)

使用Gson库,将 Java对象转换为 Json字符串

setLayoutParams()

答案 1 :(得分:0)

最简单的解决方案是循环:

StringBuilder sb = new StringBuilder("[");
for(int i = 0; i < array.length; i++) {
    sb.append(array[i]);
    if(i < array.length-1) {
        sb.append(",");
    }
}
out.write(sb.append("]").toString());

但这会产生可能无效的JSON(未转义)的问题。因此:

然而,最好的解决方案是使用适当的JSON / Java绑定库,如Jackson,Gson等。