开发者

Android JSON Exception

开发者 https://www.devze.com 2023-04-08 23:52 出处:网络
I have a little problem with parsing JSON data which I receive via server.I have a two JsonObjects which don\'t have data always,only in some cases but I need to check if they are null or not everytim

I have a little problem with parsing JSON data which I receive via server.I have a two JsonObjects which don't have data always,only in some cases but I need to check if they are null or not everytime.I'm using this code to do that :

String jsonData = new String(contentBuffer,"UTF-8");
            Log.w("JSONDATA","JSONDATA VALID OR NOT : "+jsonData);
            json = new JSONObject(jsonData);
            JSONObject jsonObj =(JSONObject) new JSONTokener(jsonData).nextValue();

if(jsonObj.getString("collection_id")==null){
                values.put("collection_id", 0);
            }else {
                collectionId = Integer.parseInt(jsonObj.getString("collection_id"));
                values.put("collection_id", collectionId);
            }   
            Log.w("COLLECTION ID ","SHOW COLLECTION ID : "+collectionId);

            if(jsonObj.getString("card_id")!=null){
                values.put("card_id", cardId);
            }else {
                values.put("card_id", 0);
            }
            Log.w("CARD ID ","SHOW CARD ID : "+cardId);

And the thing that I want it not to throw an Exception, just to check if collection_id is null, save 0 in the database, and if not save it'开发者_开发百科s value. But using this code it's throwin me JSONException.

Any ideas how to fix that?


use

   if ( jsonObject.has("collection_id"))

this will check if jsonObject has collection_id key present in it.


You could also use

collectionId = jsonObj.optInt("collection_id", 0);

This will get the value as an int if it exists, or return 0 if it does not.

0

精彩评论

暂无评论...
验证码 换一张
取 消