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

0 java arrays

我有一个像string []句子一样的字符串数组,它包含每个索引中的一个句子,如This is the first messagein sentences[0]This is the second messagein 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();
Run Code Online (Sandbox Code Playgroud)

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

Noo*_*waz 9

使用Gson库,将Java对象转换为Json String

    String[] sentences=new String[3];
    sentences[0]="Hi";
    sentences[1]="Hello";
    sentences[2]="How r u?";

    Gson gson=new GsonBuilder().create();
    String jsonArray=gson.toJson(sentences);

    //["Hi","Hello","How r u?"]

    out.write(jsonArray);
    out.flush();
    out.close();
Run Code Online (Sandbox Code Playgroud)