读取URL以使用Gson,Java解析json

时间:2014-09-30 18:22:31

标签: java json url gson

我一直在努力解析一些Json。我从一个网站获得了这个json并将其存储在本地,所以我也可以离线测试它。但现在我想更改它并直接从URL中读取它(例如http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_week.geojson)我认为这将是一项简单的任务,但我似乎无法弄明白。这是我到目前为止所拥有的一个例子。

主类:memberToJava.java

public class memberToJava {

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

        BufferedReader json = new BufferedReader(new FileReader("...Member.json")); 


        memberClass memberClass = new Gson().fromJson(json, memberClass.class);

        System.out.println("Id: " + memberClass.getMember().get(1).getId());  
    }
}

解决方案

public class memberToJava {

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

    URL url = new URL(//URL Here);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

    BufferedReader json  = new BufferedReader(new InputStreamReader(connection.getInputStream()));          

        memberClass memberClass = new Gson().fromJson(json, memberClass.class);

        System.out.println("Id: " + memberClass.getMember().get(1).getId());  
    }
}

0 个答案:

没有答案