Simplest way to read json from a URL in java

后端 未结 11 972
情书的邮戳
情书的邮戳 2020-11-22 04:15

This might be a dumb question but what is the simplest way to read and parse JSON from URL in Java?

In Groovy, it\

相关标签:
11条回答
  • 2020-11-22 05:09

    I have done the json parser in simplest way, here it is

    package com.inzane.shoapp.activity;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.util.Log;
    
    public class JSONParser {
    
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    
    // constructor
    public JSONParser() {
    
    }
    
    public JSONObject getJSONFromUrl(String url) {
    
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
    
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
    
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
                System.out.println(line);
            }
            is.close();
            json = sb.toString();
    
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
    
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
            System.out.println("error on parse data in jsonparser.java");
        }
    
        // return JSON String
        return jObj;
    
    }
    }
    

    this class returns the json object from the url

    and when you want the json object you just call this class and the method in your Activity class

    my code is here

    String url = "your url";
    JSONParser jsonParser = new JSONParser();
    JSONObject object = jsonParser.getJSONFromUrl(url);
    String content=object.getString("json key");
    

    here the "json key" is denoted that the key in your json file

    this is a simple json file example

    {
        "json":"hi"
    }
    

    Here "json" is key and "hi" is value

    This will get your json value to string content.

    0 讨论(0)
  • 2020-11-22 05:11

    It's very easy, using jersey-client, just include this maven dependency:

    <dependency>
      <groupId>org.glassfish.jersey.core</groupId>
      <artifactId>jersey-client</artifactId>
      <version>2.25.1</version>
    </dependency>
    

    Then invoke it using this example:

    String json = ClientBuilder.newClient().target("http://api.coindesk.com/v1/bpi/currentprice.json").request().accept(MediaType.APPLICATION_JSON).get(String.class);
    

    Then use Google's Gson to parse the JSON:

    Gson gson = new Gson();
    Type gm = new TypeToken<CoinDeskMessage>() {}.getType();
    CoinDeskMessage cdm = gson.fromJson(json, gm);
    
    0 讨论(0)
  • 2020-11-22 05:13

    Using the Maven artifact org.json:json I got the following code, which I think is quite short. Not as short as possible, but still usable.

    package so4308554;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.Reader;
    import java.net.URL;
    import java.nio.charset.Charset;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    public class JsonReader {
    
      private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
          sb.append((char) cp);
        }
        return sb.toString();
      }
    
      public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
          BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
          String jsonText = readAll(rd);
          JSONObject json = new JSONObject(jsonText);
          return json;
        } finally {
          is.close();
        }
      }
    
      public static void main(String[] args) throws IOException, JSONException {
        JSONObject json = readJsonFromUrl("https://graph.facebook.com/19292868552");
        System.out.println(json.toString());
        System.out.println(json.get("id"));
      }
    }
    
    0 讨论(0)
  • 2020-11-22 05:14

    If you don't mind using a couple libraries it can be done in a single line.

    Include Apache Commons IOUtils & json.org libraries.

    JSONObject json = new JSONObject(IOUtils.toString(new URL("https://graph.facebook.com/me"), Charset.forName("UTF-8")));
    
    0 讨论(0)
  • 2020-11-22 05:15

    Here are couple of alternatives versions with Jackson (since there are more than one ways you might want data as):

      ObjectMapper mapper = new ObjectMapper(); // just need one
      // Got a Java class that data maps to nicely? If so:
      FacebookGraph graph = mapper.readValue(url, FaceBookGraph.class);
      // Or: if no class (and don't need one), just map to Map.class:
      Map<String,Object> map = mapper.readValue(url, Map.class);
    

    And specifically the usual (IMO) case where you want to deal with Java objects, can be made one liner:

    FacebookGraph graph = new ObjectMapper().readValue(url, FaceBookGraph.class);
    

    Other libs like Gson also support one-line methods; why many examples show much longer sections is odd. And even worse is that many examples use obsolete org.json library; it may have been the first thing around, but there are half a dozen better alternatives so there is very little reason to use it.

    0 讨论(0)
提交回复
热议问题