java 从字符串(gson)的显示中删除反斜杠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34201080/
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
remove backslash from display of string(gson)
提问by user3569530
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\"]"}
而 jsonObject 是 {"test":"[\"aaa\",\"bbb\",\"ccc\"]"}
but i need get following {"test":["aaa","bbb","ccc"]}
但我需要关注 {"test":["aaa","bbb","ccc"]}
What the way to do this?
有什么办法做到这一点?
replaceAll in several ways is not solving this problem
以多种方式replaceAll并不能解决这个问题
回答by Alexis C.
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.
您正在添加一个键值映射String -> String
,这就是引号被转义的原因(实际上您的值是该toString()
方法给出的列表的字符串表示)。如果需要映射String -> Array
,则需要将列表转换为 aJsonArray
并将其添加为属性。
jsonObject.add("test", gson.toJsonTree(exampleList, new TypeToken<List<String>>(){}.getType()));
回答by Viacheslav Vedenin
Don't mix Gson and JsonObject,
不要混合使用 Gson 和 JsonObject,
1) if you need {"test":["aaa","bbb","ccc"]} using GSON you should define
1) 如果你需要 {"test":["aaa","bbb","ccc"]} 使用 GSON 你应该定义
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
2) 如果你需要 {"test":["aaa","bbb","ccc"]} 使用 JsonObject 你应该添加
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.
但是永远不要尝试混合使用 Gson 和 JsonObject,因为 jsonObject.addProperty("test", text) 不允许将文本添加为 json 并且总是转义此文本。
回答by ankit prajapati
String jsonFormattedString = jsonStr.replaceAll("\\", "");
Use this for remove \
from string of object.
使用它\
从对象字符串中删除。