java - 字符串到 Json 转义嵌套 json 中的正斜杠
问题描述
我想将字符串转换为 JSON。java gson 的 JsonObject。该字符串是一个嵌套的 JSON 结构,其中添加了正斜杠 (),正如您在名称中看到的那样,它有 \\"。(一个 \ 用于转义 \,一个 \ 用于“。
如何忽略内部 \ 并转换为 JSON 对象。我试图用 replaceAll 来转义 \\" 但没有工作,因为它也替换了 \"
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
public static void main(String args[]){
String json = "[{\"key\":\"px\",\"mKeyValues\":[{\"hmKey\":\"qx\",\"value\":\"[{\\\"name\\\":\\\"Test Equipment value\\\",\\\"status\\\":\\\"2\\\"}]\"}]}]";
JsonParser jsonParser = new JsonParser();
json = json.replaceAll("\\\\","");
System.out.println(json);
JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
System.out.println(jsonObject);
}
}
实际的 Json 是
[
{
"key": "px",
"mKeyValues": [
{
"hmKey": "qx",
"value": [
{
"name": "Test Equipment value",
"status": "2"
}
]
}
]
}
]
解决方案
这会成功的
json = json.replace("\"[","[").replace("]\"", "]").replace("\\\"", "\"");
无需更换的解决方案
public static void main(String[] args)
String json = "[{\"key\":\"px\",\"mKeyValues\":[{\"hmKey\":\"qx\",\"value\":\"[{\\\"name\\\":\\\"Test Equipment value\\\",\\\"status\\\":\\\"2\\\"}]\"}]}]";
System.out.println(json);
JsonParser jsonParser = new JsonParser();
JsonArray jsonObject = jsonParser.parse(json).getAsJsonArray();
JsonObject mKeyValues0 = jsonObject.get(0).getAsJsonObject()
.get("mKeyValues").getAsJsonArray()
.get(0).getAsJsonObject();
mKeyValues0.add("value", jsonParser.parse(mKeyValues0.get("value").getAsString() ));
System.out.println(jsonObject);
}
推荐阅读
- javascript - 我可以枚举仅作为 getter/setter 函数存在的属性吗?
- c++ - 在虚幻引擎 4 中将嵌套的 json 解析为 TMap
- flutter - 并排显示按钮 | 不显眼的方法?
- html - 如何使用 Sublime Text 查找多行属性
- r - 在 R 中进行多重匹配后,如何从 2 个数据帧中乘以列值
- flutter - 在 Flutter 中将一列居中在另一列中
- haskell - 带有状态的管道`run`
- ios - 更新以编程方式创建的标签导航栏项
- python - 在这种情况下如何使用 pandas read_csv?
- rust - 如何生成带有滑动窗口对的迭代器?