3

I have the list

Gson gson = new Gson();

List<String> exampleList = new ArrayList<String>();
exampleList.add("aaa");
exampleList.add("bbb");
exampleList.add("ccc");

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("test", gson.toJson(exampleList));

And jsonObject is {"test":"[\"aaa\",\"bbb\",\"ccc\"]"}

but i need get following {"test":["aaa","bbb","ccc"]}

What the way to do this?

replaceAll in several ways is not solving this problem

user3569530
  • 193
  • 2
  • 4
  • 13
  • as one of many ways jsonObject.addProperty("test", gson.toJson(exampleList).replace("\\","")); but this does not work, and in common sence - string not contains backslash, this is problem of display(and my http(post) request which i try do) – user3569530 Dec 10 '15 at 11:52
  • @rakeshkr no, please don't use replaceAll, try to understand what is wrong – Ruan Mendes Dec 10 '15 at 11:53
  • sonObject.addProperty("test", exampleList) - in this case i need string value this backslahes – user3569530 Dec 10 '15 at 11:56

3 Answers3

5

You're adding a key-value mapping String -> String, that is why the quotes are escaped (in fact your value is the string representation of the list given by the toString() method). If you want a mapping String -> Array, you need to convert the list as a JsonArray and add it as a property.

jsonObject.add("test", gson.toJsonTree(exampleList, new TypeToken<List<String>>(){}.getType()));
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
1

Don't mix Gson and JsonObject,

1) if you need {"test":["aaa","bbb","ccc"]} using GSON you should define

public class MyJsonContainer {
   List<String> test = new ArrayList<String>();
   ...
   // getter and setter
}

and use

List<String> exampleList = new ArrayList<String>();
exampleList.add("aaa");
exampleList.add("bbb");
exampleList.add("ccc");
MyJsonContainer jsonContainer = new MyJsonContainer();
jsonContainer.setTest(exampleList);
String json = gson.toJson(jsonContainer); // this json has {"test":["aaa","bbb","ccc"]}

2) if you need {"test":["aaa","bbb","ccc"]} using JsonObject you should just add

List<String> exampleList = new ArrayList<String>();
exampleList.add("aaa");
exampleList.add("bbb");
exampleList.add("ccc");

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("test", exampleList);

But never try to mix Gson and JsonObject, because jsonObject.addProperty("test", text) does not allowed to add text as json and allways escaped this text.

Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
  • You got a good point Viacheslav, but the code proposed -> jsonObject.addProperty("test", exampleList); Gives an error -> The method addProperty(String, String) in the type JsonObject is not applicable for the arguments (String, List). The solution for this error is Gson().toJsonTree(object) – jfajunior Oct 16 '18 at 08:51
0
String jsonFormattedString = jsonStr.replaceAll("\\\\", "");

Use this for remove \ from string of object.