0

In this method, I have an array of strings i.e barchartLabels. I want to add this array to jsonObject:

Expected output is :

{ "data" : " [ "January", "February", "March", "April", "May", "June", "July" ] " }

public String array() {
    JsonArray roleArray = new JsonArray();
    String barChartLabels[] = {"January", "February", "March", "April", "May", "June", "July"};
    Gson listG = new Gson();
    JsonObject jsonObj = new JsonObject();
    String list2 = listG.toJson(barChartLabels);
    jsonObj.addProperty("data", list2);
    roleArray.add(jsonObj);    
    return  jsonObj.toString(); 
}

In the above method I'm using Gson object to convert barchartLabels to string then using jsonObject adding it. But I'm getting the output as shown below. Is there any other way to do the above mentioned?

{ "data" : " [ \"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\" ] " }

4
  • 2
    It is the standard json format to escapse " so don't worry Commented Jun 2, 2017 at 10:49
  • This is webservice which is mentioned above. In the UI after getting response i'm retriveing this array from json and assigning it to array in UI ...which is creating problem ... Commented Jun 2, 2017 at 10:55
  • This is not a problem, all that is happening is that your " " are being escaped. As @Pavneet_Singh has mentioned, this is completely standard. Commented Jun 2, 2017 at 10:57
  • @SabnekarRajnikant please check my updated answer Commented Jun 2, 2017 at 13:59

1 Answer 1

4

data is a String, not a String[], so all the quotes are escaped. If you want a String[] just

    JsonArray data = new JsonArray();
    Stream.of(barChartLabels)
         .forEach(data::add);
    jsonObj.add("data", data);

listG.toJson is converting it to a JSON String, so when you add that, it's a String. Just skip that step and add it directly

Sign up to request clarification or add additional context in comments.

7 Comments

method addproperty(string,string) in the jsonObject is not applicable for arguements(string,string[])
You could make this simpler by skipping the array and just starting with a Stream.of("foo", "bar", "etc...")
method add(string,JsonElement) in the jsonObject is not applicable for arguements(string,string[])
@SabnekarRajnikant You commented after I updated the answer. Please look at the edit
Sorry this is taking so long, I use POJOs and Jackson, so had to learn the Gson stuff
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.