madhu sudhan
madhu sudhan

Reputation: 1

How do I convert String array into Json Array

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

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?

Upvotes: 0

Views: 21996

Answers (2)

Noor Nawaz
Noor Nawaz

Reputation: 2225

Use Gson library, which convert Java object to 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();

Upvotes: 12

ernest_k
ernest_k

Reputation: 45339

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:

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

Upvotes: 0

Related Questions