首页 > 解决方案 > 字符串到 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"
          }
        ]
      }
    ]
  }
]

标签: javajsongson

解决方案


这会成功的

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

推荐阅读