java 如何将字符串数组转换为 Json 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35250698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:54:41  来源:igfitidea点击:

How do I convert String array into Json Array

javaarrays

提问by madhu sudhan

I have a string array like string[] sentences which consist of sentences one in each index like This is the first messagein sentences[0]and This is the second messagein sentences[1]and so on. My java code to send the information to the server for sentiment analysis is like this:

我有一个像 string[] 句子这样的字符串数组,它由每个索引中的一个句子组成,例如This is the first messageinsentences[0]This is the second messageinsentences[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();

How do I replace the texts above in the code by the string array for it's length say n?

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

回答by Noor Nawaz

Use Gsonlibrary, which convert Java objectto Json String

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

    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();

回答by ernest_k

The easiest solution is a loop:

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

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());

But this has the problem of producing potentially invalid JSON (unescaped). Hence:

但这存在产生潜在无效 JSON (unescaped) 的问题。因此:

The best solution, however, would be to use a proper JSON/Java binding library such as Hymanson, Gson, etc.

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