Geo Thomas
Geo Thomas

Reputation: 1159

How to fix com.google.gson.stream.MalformedJsonException

I am trying to read a file from an external URL. The file contains data in JSON format. I am using the following code to read data from the file:

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

But I am getting the following exception while trying to run the code:

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

How can I fix this error? I have been spending some time now online to find s solution, but nothing helped me.

I am adding the sample data below:

{"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"}

Upvotes: 0

Views: 25135

Answers (2)

Naor Bar
Naor Bar

Reputation: 2209

To your first question, MalformedJsonException indicates that your input might not be a valid json; I would check that with an online json formatter/validator, such as this one before ignoring with setLenient(true).

To your second question: how o construct a Json array with multiple URLs, this is one way to do it:

    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...
    }

An update:

I checked your URL, and as I stated before it's an invalid json. In this case, you'll have get the request content as a string and convert it to a valid json manually (add brackets). Then the parsing will work.

This code will do it:

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

Upvotes: 2

Wulf
Wulf

Reputation: 712

Maybe this will help...

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

Upvotes: 2

Related Questions