有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Jayway在JAVA中解析同时具有转义和Unescape字符的JSON

我收到以下json作为我的程序的输入:

{
    "shopping": {
        "cart": {
            "items": [{
                "iturl" : "https://www.google.com/",
                "itdesc" : "Item’s box includes the below contents:\n a.adaptor \n b.sdfd"
            }]
        }
    }
}

我们正在使用jayway jsonpath解析这些数据,并进行一些处理,然后以字符串形式返回最终值

当我们使用默认的jsonpath配置解析它时,我将iturl修改为“https:\/\/www.google.com\/”

已尝试将JSONProvider更改为JacksonJsonProvider(通过引用Jsonpath with Jackson or Gson),url问题已得到解决,但itdesc的值现在变为新行(由于\n),使其成为无效的json

我无法具体处理每个字段,因为传入的数据将是动态的

有没有合适的方法在java中解析这种JSON。提前谢谢你的帮助


共 (2) 个答案

  1. # 1 楼答案

    尝试在解析字符串之前再添加一个转义级别,字符串解析器将为“\\n”提供“\n”

    例如,使用Jackson ObjectMapper进行解析

    objectMapper.readValue(jsonString.replace("\\", "\\\\"), Any.class);
    
  2. # 2 楼答案

    {
    "shopping": { <  JSONObject
        "cart": { <  JSONObject
            "items": [{ <  JSONArray
                "iturl" : "https://www.google.com/", <  JSONObject inside JSONAray
                "itdesc" : "Item’s box includes the below contents:\n a.adaptor \n b.sdfd"
            }]
        }
    }
    

    }

    如果这个数据来自http连接。 此json必须是字符串格式First, 尝试使用org。json。易于理解的 所以你要这样做:

    private void readData() {
        String Body = (response json string from connection);
        JSONParser parse = new JSONParser();
        String iturl = null;
        String itdesc = null;
    
        try  {
            JSONObject shopping =  (JSONObject) parse.parse(Body);
            JSONObject cart=  (JSONObject) shopping.get("cart");
            JSONArray  items = (JSONArray  ) cart.get("items ");
            items.forEach((k)-> {
                JSONObject inside = (JSONObject) k;
                iturl = inside.get("iturl");
                itdesc = inside.get("itdesc");
            });
        }catch ( ParseException e) {
            e.printStackTrace();
        }
    
    }
    

    如果这是文件。json与阅读器的结合:

    private static final File jsonData = new File(file.json);
    private void callData() {
        String iturl = null;
        String itdesc = null;
        try  {
            Reader reader = new FileReader(marketList);
            JSONParser parse = new JSONParser();
            JSONObject shopping =  (JSONObject) parse.parse(reader);
            JSONObject cart=  (JSONObject) shopping.get("cart");
            JSONArray  items = (JSONArray  ) cart.get("items ");
            items.forEach((k)-> {
                JSONObject inside = (JSONObject) k;
                iturl = inside.get("iturl");
                itdesc = inside.get("itdesc");
            });
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }