1

I'm trying to read json by url. This is my effort:

 public String getContentByUrl(String url) throws IOException, JSONException {

        JSONObject json = new JSONObject(IOUtils.toString(new URL(url), Charset.forName("UTF-8")));
        return json.toString();
    }

Throws

A JSONObject text must begin with '{' at 2 [character 3 line 1]

Also I tried JSONPObject, but it hasn't got such constructor. What do?

Tony
  • 3,605
  • 14
  • 52
  • 84
  • 2
    Well what does the response look like? Seems like it is not valid JSON. – germi May 06 '15 at 08:34
  • @germi, http://jsonformatter.curiousconcept.com/ says it is a valid json. – Tony May 06 '15 at 08:35
  • Put the result of `IOUtils.toString(new URL(url), Charset.forName("UTF-8"))` in a string and log it. – Biffen May 06 '15 at 08:36
  • @Biffen, do you mean the problem is related to encoding? – Tony May 06 '15 at 08:37
  • @Tony I don't know what it could be, but encoding is a good guess (what made you choose UTF-8?). Logging the string is just a step in the troubleshooting. – Biffen May 06 '15 at 08:40

1 Answers1

1

Based on my knowledge and the JSON API there is only one JSONObject constructor that your try with a String.

In the API it says that the String source has to be:

A string beginning with { (left brace) and ending with } (right brace).

The typical usecase therefore is to request the page content and parse the result as a JSONObject via the constructor, instead of passing a complete URL. Which is already described in several posts on stackoverflow (e.g. Get a JSON object from a HTTP response)

EDIT:

I guess the http://jsonformatter.curiousconcept.com/ accepts the content of your URL as legit JSON is because it recognises the brackets ([ ]) as a JSONArray.

If you put your "JSON" into http://jsonlint.com/ for example it shows you pretty much why it can't be a JSONObject.

Community
  • 1
  • 1
ceekay
  • 471
  • 3
  • 14