GSON 将字符串转换为 JSON,值中包含 url

问题描述 投票:0回答:1

我使用

toString()
方法将 Map 对象转换为 String。但是,它从每个键和值中去掉了双引号

{title=mytitle, iss=https://google.com}
instead of 
{"title"="mytitle", "iss"="https://google.com"}

然后当我尝试使用

GSON
将其转换为 JSON 对象时,

Map<String, ? extends Object> objectMap= GSON.fromJson(myMap.toString(), Map.class);

遇到了。

Unterminated object at line 1 column 34 path $.

我可以看到导致问题的正斜杠

是否有任何 API 或函数可以用来在将地图对象转换为字符串时保留双引号,或者有任何方法可以让 GSON 避免

/
验证?我尝试了
setLient()
但没有成功。

编辑: 我不能使用

GSON.toJson(object)
的原因是因为这个 thread GSON 将数组解析为 TreeMap,因为
values
条目下有额外的
role

java json gson
1个回答
0
投票

“...我使用

toString()
方法将 Map 对象转换为 String。但是,它从每个键和值中去掉了双引号...”

注意,这些结构一开始就不可互换。
只有 JSON 对象 才会被视为 mapdictionary

此外,Map 对于每个条目使用等号,而不是冒号

如果JSON很简单,只需实现您自己的。

StringBuilder s = new StringBuilder();
for (Map.Entry<String, String> e : m.entrySet()) {
    if (!s.isEmpty()) s.append(", ");
    s.append("\"%s\": \"%s\"".formatted(e.getKey(), e.getValue()));
}
s.insert(0, '{').append('}');

输出

{"title": "mytitle", "iss": "https://google.com"}
© www.soinside.com 2019 - 2024. All rights reserved.