user3569530
user3569530

Reputation: 193

remove backslash from display of string(gson)

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

Upvotes: 3

Views: 15544

Answers (3)

ankit prajapati
ankit prajapati

Reputation: 1

String jsonFormattedString = jsonStr.replaceAll("\\\\", "");

Use this for remove \ from string of object.

Upvotes: 0

Slava Vedenin
Slava Vedenin

Reputation: 60104

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.

Upvotes: 1

Alexis C.
Alexis C.

Reputation: 93842

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

Upvotes: 5

Related Questions