Android中从网页获取JSON解析或者使用Gson解析示例

public class Event {

    /** Title of the earthquake event */
    
public final String title;

    /** Time that the earthquake happened (in milliseconds) */
    
public final long time;

    /** Whether or not a tsunami alert was issued (1 if it was issued, 0 if no alert was issued) */
    
public final int tsunamiAlert;

    /**
     * Constructs a new {
@link Event}.
     *
     *
@param eventTitle is the title of the earthquake event
     *
@param eventTime is the time the earhtquake happened
     *
@param eventTsunamiAlert is whether or not a tsunami alert was issued
     */
    
public Event(String eventTitle, long eventTime, int eventTsunamiAlert) {
        title = eventTitle;
        time = eventTime;
        tsunamiAlert = eventTsunamiAlert;
    }
}

 

 

 

详情soonami

1. 从网页获取json数据(通过HttpURLConnection

private String makeHttpRequest(URL url) throws IOException {
            String jsonResponse = "";
//            HttpURLConnection urlConnection = null;
            HttpURLConnection urlConnection = null;
            InputStream inputStream = null;

            try {
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setReadTimeout(10000 /* milliseconds */);
                urlConnection.setConnectTimeout(15000 /* milliseconds */);
                urlConnection.connect();
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            } catch (IOException e) {
                // TODO: Handle the exception
                
e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (inputStream != null) {
                    // function must handle java.io.IOException here
                    inputStream.close();
                }
            }
            return jsonResponse;
        }

2. 调用extractFeatureFromJson解析

https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2012-01-01&endtime=2012-12-01&minmagnitude=6

Json代码来源

通过http://jsonprettyprint.com/ 转换json数据使得数据可视化

其中一段数据和代码对应如下所示

JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);

 

{

  "type": "FeatureCollection",

  "metadata": {

    "generated": 1526637645000,

    "url": "https:\/\/earthquake.usgs.gov\/fdsnws\/event\/1\/query?format=geojso    "title": "USGS Earthquakes",

    "status": 200,

    "api": "1.5.8",

    "count": 122

  },

JSONArray featureArray = baseJsonResponse.getJSONArray("features");

 

"features": [

 

{

JSONObject firstFeature = featureArray.getJSONObject(0);

 

      "type": "Feature", 

      "properties": {

String title = properties.getString("title");

        "mag": 6,

        "place": "New Britain region, Papua New Guinea",

long time = properties.getLong("time");

 

        "time": 1353318274120,

        "updated": 1507753181020,

        "tz": null,

        "url": "https:\/\/earthquake.usgs.gov\/earthquakes\/eventpage\/usp000jvtm",

        "detail": "https:\/\/earthquake.usgs.gov\/fdsnws\/event\/1\/query?eventid=usp000jvtm&format=geojson",

        "felt": null,

        "cdi": null,

        "mmi": 5.3,

        "alert": null,

        "status": "reviewed",

int tsunamiAlert = properties.getInt("tsunami");

        "tsunami": 0,

        "sig": 554,

        "net": "us",

        "code": "p000jvtm",

        "ids": ",choy20121119094434,usp000jvtm,atlas20121119094434,",

        "sources": ",choy,us,atlas,",

        "types": ",focal-mechanism,impact-text,moment-tensor,moment-tensor,moment-tensor,origin,phase-data,shakemap,",

        "nst": 430,

        "dmin": null,

        "rms": 0.88,

        "gap": 12.4,

        "magType": "mww",

        "type": "earthquake",

        "title": "M 6.0 - New Britain region, Papua New Guinea"

      },

 

3.ExtractFeatureFromJson代码如下

 

private Event extractFeatureFromJson(String earthquakeJSON) {
    try {
        JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
        JSONArray featureArray = baseJsonResponse.getJSONArray("features");

        // If there are results in the features array
        if (featureArray.length() > 0) {
            // Extract out the first feature (which is an earthquake)
            JSONObject firstFeature = featureArray.getJSONObject(0);
            JSONObject properties = firstFeature.getJSONObject("properties");

            // Extract out the title, time, and tsunami values
            String title = properties.getString("title");
            long time = properties.getLong("time");
            int tsunamiAlert = properties.getInt("tsunami");

            // Create a new {@link Event} object
            return new Event(title, time, tsunamiAlert);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
    }
    return null;
}

显示结果如下

 

JSONObject和JSONArray的数据表示形式

JSONObject的数据是用 { } 来表示的,

例如:

{

    "id":"1",

    "courseID":"化学",

    "title":"滴定实验",

    "content":"下周二实验楼201必须完成"}

JSONArray,顾名思义是由JSONObject构成的数组,用 [ { } , { } , …… , { } ] 来表示

例如:

[

    {

        "id":"1",

        "courseID":"数学",

        "title":"一加一等于几"

    },

    {

        "id":"2",

        "courseID":"语文",

        "title":"请背诵全文"

    }

]


表示了包含2个JSONObject的JSONArray。

可以看到一个很明显的区别,一个最外面用的是 { } ,一个最外面用的是 [ ] ;

 

Android 中的Gson 使用示例:

首先建立一个class

public class User {
    private String name;
    private int age;
    public User(String name, int age){
        this.name = name;
        this.age = age;
    }
    public String getName(){return name;}
    public int getAge(){return age;}

}

 

然后

import com.google.gson.Gson;

 

自己定义一段JSON数据然后解析

public class Gsontest1 {
    private static void log(String msg){
        System.out.println(msg);
    }
    public static void main(String [] args)throws Exception{
        //五月 ごがつ(五月)さつき
        Gson gson = new Gson();
        User user = new User("luoziling",20);
        String JsonObject = gson.toJson(user);
        System.out.println(JsonObject);
        String jsonString = "{\"name\":\"satsuki\",\"age\":21}";
        User user1 = gson.fromJson(jsonString,User.class);
        System.out.println(user1.getName());
        System.out.println(user1.getAge());

    }
}

 

运行结果如下

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值