如何修复com.google.gson.stream.MalformedJsonException

时间:2018-05-15 09:07:25

标签: java json

我正在尝试从外部URL读取文件。该文件包含JSON格式的数据。我使用以下代码从文件中读取数据:

URL url = new URL(url);
URLConnection request = url.openConnection();
request.connect();JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
JSONObject jsonObject = new JSONObject(rootobj.toString()); 

但是在尝试运行代码时遇到以下异常:

com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 2 column 2 

如何修复此错误?我现在花了一些时间在线寻找解决方案,但没有任何帮助。

我正在添加以下示例数据:

{"address":"P.O. Box 939","city":"Indian River","country":"US","dateAdded":"2018-02-08T04:35:45Z","dateUpdated":"2018-02-08T04:35:45Z","descriptions":[{"dateSeen":["2018-02-01T21:34:00.000Z"],"sourceURLs":["https://www.weddingwire.com/biz/rental-express-indian-river/2274f039e0c45443.html"],"value":"Contact Rental Express in Indian River on WeddingWire. Browse Event Rentals prices, photos and 1 reviews, with a rating of 5.0 out of 5"}],"features":[{"key":"Average Rating","value":["5.0"]},{"key":"Event Items","value":["Chairs","Dance Floor","Lights","Photobooth","Tables","Tent Accessories","Tents"]},{"key":"Food/Beverage Items","value":["China","Flatware","Glassware","Linens"]}],"keys":["us/mi/indianriver/p.o.box939/-1646083636"],"latitude":"45.4125117","longitude":"-84.6125364","name":"Rental Express","phones":["2312389696"],"postalCode":"49749","province":"MI","sourceURLs":["https://www.weddingwire.com/biz/rental-express-indian-river/2274f039e0c45443.html"],"id":"AWFztIreIxWefVJwy6hK"}
{"address":"PO Box 6479","city":"Silver Spring","country":"US","dateAdded":"2018-02-08T04:35:35Z","dateUpdated":"2018-02-08T04:35:35Z","descriptions":[{"dateSeen":["2018-02-01T06:27:00.000Z"],"sourceURLs":["https://www.weddingwire.com/biz/indian-spring-country-club-silver-spring/9c020a063ea0fc84.html"],"value":"Contact Indian Spring Country Club in Silver Spring on WeddingWire. Browse Venue prices, photos and 3 reviews, with a rating of 4.3 out of 5"}],"features":[{"key":"Average Rating","value":["4.3"]}],"keys":["us/md/silverspring/pobox6479/1573156840"],"name":"Indian Spring Country Club","phones":["3018716000"],"postalCode":"20916","province":"MD","sourceURLs":["https://www.weddingwire.com/biz/indian-spring-country-club-silver-spring/9c020a063ea0fc84.html"],"id":"AWFztWW0IxWefVJwy7PH"}

2 个答案:

答案 0 :(得分:1)

对于您的第一个问题, MalformedJsonException 表示您的输入可能不是有效的json;我会使用在线json格式化程序/验证程序检查,例如this,然后忽略 setLenient(true)

关于你的第二个问题:如何用多个URL构建一个Json数组,这是一种方法:

    try {
        // Here I use github api as a sample service:
        URL url1 = new URL("https://api.github.com/users/n1");
        URL url2 = new URL("https://api.github.com/users/n2");

        List<URL> urlsList = new ArrayList<URL>();
        urlsList.add(url1);
        urlsList.add(url2);

        JsonArray jsonArr = new JsonArray();
        for (URL url : urlsList) {
            URLConnection request = url.openConnection();
            request.connect();
            JsonObject jsonObj = new JsonParser().parse(new InputStreamReader((InputStream) request.getContent())).getAsJsonObject();
            jsonArr.add(jsonObj);   
        }
        System.out.println(jsonArr.toString());
    } catch (Exception e) {
        // do something here...
    }

更新:

我检查了你的网址,正如我之前说的那样,这是一个无效的json。 在这种情况下,您将获取请求内容作为字符串并手动将其转换为有效的json(添加括号)。然后解析将工作。

此代码将执行此操作:

    try {
        URL url = new URL("http://d1kv7s9g8y3npv.cloudfront.net/testsite/files/doc-lib/2018/05/15/04/01/09/142/head/test.txt.txt");
        URLConnection request = url.openConnection();
        request.connect();
        BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        String content = rd.lines().collect(Collectors.joining());
        JsonElement jsonElement = new JsonParser().parse("["  + content + "]");
        System.out.println(jsonElement.toString());
    } catch (Exception e) {
        // do something here...
        System.out.println(e.getMessage());
    }

答案 1 :(得分:0)

也许这会有所帮助......

JsonReader jr = new JsonReader(new InputStreamReader((InputStream) request.getContent()));
jr.setLenient(true); //like the expetion says to accept the malformed json
JsonElement root = jp.parse(jr);

https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/stream/JsonReader.html#setLenient-boolean-

https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonParser.html