Parse JSON with optional field

纵然是瞬间 提交于 2019-12-04 19:29:48

best way to handle optional fields in JSON is to use opt instead of get

opt provides the parsed value if exist or default value for that datatype if requested key does not exist.

best thing is, it don't even need a try catch block since it always returns a value and in case of any error from server, it will not let your app crash or prevent other values from being parsed.

String location = response.optString("location");

if location exist in response, then it will initialize with the value or it will leave the string null. in case of int or long default is 0, in case of boolean default is false. read about opt for more details.

Use has() method

    JSONArray stops = jsonObj.getJSONArray("stops");

    for (int i = 0; i < stops.length(); i++) {
        JSONObject c = stops.getJSONObject(i);

        String num = c.getString("num");
        String time = c.getString("time");
        String title = c.getString("title");
        String descripcion = c.getString("desc");
        String type = c.getString("type");
        String subtype = c.getString("subtype");
        if(c.has("location") && !c.isNull("location")){
            // parse location
        }

        if(c.has("images") && !c.isNull("images")){
            // parse images
        }

            .....
    }

you should use Retrofit and Google Gson, where you do not have to do lot of work, they will do the job for you. look at these

https://guides.codepath.com/android/Consuming-APIs-with-Retrofit

http://www.vogella.com/tutorials/Retrofit/article.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!