1

I have to create JSON parser to save data received from url into JSON object using org.json library and only java standard libraries but I have no idea how to connec to those

 String line = "326";

    URL oracle = new URL("https://api.tfl.gov.uk/Line/"+line+"/Arrivals?app_id=&app_key=");
    BufferedReader in = new BufferedReader(
    new InputStreamReader(oracle.openStream()));

    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();

This my connection code

2 Answers2

0

My suggestion would be to use a JSON parser such as Jackson.

  1. Create a class that would store the data you want to store from that JSON.
  2. Use URL to connect and grab the JSON
  3. Use Jackson to convert it to a Java object

Let me know if you need more help and I can provide it.

j1nrg
  • 116
  • 14
  • Can you specify how to grab this JSON? It's my first attempt with URL and JSON format and –  Aug 11 '16 at 21:06
  • Check my answer on how to make http call and parse the incoming string body – faizan Aug 11 '16 at 21:10
  • There are multiple other stackoverflow answers that can show you how to pull it step by step. Ill link a few here: http://stackoverflow.com/questions/7467568/parsing-json-from-url http://stackoverflow.com/questions/4308554/simplest-way-to-read-json-from-a-url-in-java – j1nrg Aug 11 '16 at 21:23
  • Thanks, I'm getting some progress although now I'm getting error: –  Aug 11 '16 at 21:51
  • org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1] null at org.json.JSONTokener.syntaxError(JSONTokener.java:432) at org.json.JSONObject.(JSONObject.java:184) at org.json.JSONObject.(JSONObject.java:310) at GetData.WasteOfTime.main(WasteOfTime.java:31) –  Aug 11 '16 at 21:51
  • I know that its to do with the first symbol on the website I read data from not being {, but is there any way to ignore first symbol while using BufferedReader –  Aug 11 '16 at 21:52
0

Use an http client library like okhttp to make the request and get the string body.

Then use a json parser like Jackson to parse the received string into Json object.

Use okhttp as below:

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url(url)
  .build();

Response resp = client.newCall(request).execute();
String response =  resp.body().string();

Once you have the response string you can make a jsonNode from it by using Jackson ObjectMapper as below

ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(response);

Or get your defined POJO by parsing the response as

YourClass mappedPOJO = mapper.readValue(response, YourClass.class);

Lets say your incoming json was

{
    "key1":"value1",
    "key2": {
        "key3":"value3"
    }
}

Then tree.get("key1") gives you "value1",

tree.get("key1").get("key2") gives you "value3"

faizan
  • 578
  • 5
  • 14