Simplest Way to Read Json from a Url in Java

Parsing JSON from URL

  1. First you need to download the URL (as text):

    private static String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {
    URL url = new URL(urlString);
    reader = new BufferedReader(new InputStreamReader(url.openStream()));
    StringBuffer buffer = new StringBuffer();
    int read;
    char[] chars = new char[1024];
    while ((read = reader.read(chars)) != -1)
    buffer.append(chars, 0, read);

    return buffer.toString();
    } finally {
    if (reader != null)
    reader.close();
    }
    }
  2. Then you need to parse it (and here you have some options).

    • GSON (full example):

      static class Item {
      String title;
      String link;
      String description;
      }

      static class Page {
      String title;
      String link;
      String description;
      String language;
      List<Item> items;
      }

      public static void main(String[] args) throws Exception {

      String json = readUrl("http://www.javascriptkit.com/"
      + "dhtmltutors/javascriptkit.json");

      Gson gson = new Gson();
      Page page = gson.fromJson(json, Page.class);

      System.out.println(page.title);
      for (Item item : page.items)
      System.out.println(" " + item.title);
      }

      Outputs:

      javascriptkit.com
      Document Text Resizer
      JavaScript Reference- Keyboard/ Mouse Buttons Events
      Dynamically loading an external JavaScript or CSS file
    • Try the java API from json.org:

      try {
      JSONObject json = new JSONObject(readUrl("..."));

      String title = (String) json.get("title");
      ...

      } catch (JSONException e) {
      e.printStackTrace();
      }

Easy way to Get JSON From URL

You can use third party libraries like volley, retrofit....
for example with volley you should make a JsonArrayRequest to the server and parse it.

Farsi resource

English resource

and this is a basic request:

JsonArrayRequest jarr = new JsonArrayRequest(Request.Method.GET, URL, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {

try{

for(int i=0;i<response.length();i++){
JSONObject job = response.getJSONObject(i);
String name = job.getString("name");

}

} catch (Exception e){


}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {


}
});

requestQueue.add(jarr);

how i get JSON as string from url (java)

You can use Spring's RestTemplate to get the response as String, e.g.:

RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("https://www.instagram.com/ihanan95/?__a=1", String.class);
System.out.println(response);

If you are not allowed to use third party libaries then you can do the same with URLConnection, e.g.:

URLConnection connection = new URL("https://www.instagram.com/ihanan95/?__a=1").openConnection();
try(Scanner scanner = new Scanner(connection.getInputStream());){
String response = scanner.useDelimiter("\\A").next();
System.out.println(response);
}

How to parse JSON data form URL?

You need to deserialize a list of ProDesc objects because your main JSON is an array.

This is how I deserialize something similar with Jackson 2.1.4:

List<ProDesc> proDescList = objMapper.readValue(jsondata, objMapper.getTypeFactory().constructParametricType(List.class, ProDesc.class));

EDIT: If your ProDesc class contains only the id member, you need to tell Jackson to ignore the other members with an annotation like so:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown=true)
public class ProDesc {

private int id;

public ProDesc(){}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}
}


Related Topics



Leave a reply



Submit