在Json解析过程中,我为什么用object1.optInt ,和 object1.optString

本文通过实例探讨了JSON解析中getString与optString方法的区别及使用技巧。解析时若使用getString方法且目标字段不存在,则会导致程序异常;而optString则更加安全,避免此类问题。文章还列举了一些常见JSON操作如optInt与optString的具体行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 今天在做Json解析的时候,出现了一段代码没执行的问题,于是找了一下原因:

1、原代码是:

  发现 红色的一句 没有执行,查看控制台发现了异常

    

 

2、修复bug ,正确的代码为

      

 

3、总结

   1、我们解析方法getString(“ ”)是因为JSON里面不存在这个value ,会报异常,导致下面的代码不会执行

   2、安全起见我一般都是用optString方法,这种方式不会报异常

   3、object1.optInt( "id" )   不存在这个value, 返回 0

          object1.optString( "mobile" )   不存在这个value, 返回 空

 

package com.lc.bailingbird.conn; import android.content.Context; import android.text.TextUtils; import android.util.Log; import com.google.gson.Gson; import com.lc.bailingbird.base.BaseApplication; import com.lc.bailingbird.util.TextUtil; import com.zcx.helper.http.AsyGet; import com.zcx.helper.http.note.HttpFinish; import com.zcx.helper.http.note.HttpServer; import org.json.JSONObject; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import okhttp3.Headers; /** * Created by Administrator on 2017/2/3. */ @HttpFinish(true) @HttpServer(Conn.SERVICE_LT) public class BaseAsyGetLT<T> extends AsyGet<T> { private Context context; public BaseAsyGetLT(BaseAsyCallBack<T> asyCallBack) { super(asyCallBack); context = asyCallBack.context; } /** * 解析响应头数据,会在parser前被调用 * * @param headers */ @Override protected void parserHeaders(Headers headers) { if (!TextUtils.isEmpty(headers.get("token"))) { Log.e("parserHeaders: ", headers.get("token")); // BaseApplication.MYMMKV.encode("token", headers.get("token")); header("token", "63633bd12e294da5b7dcf949ac526d75"); } } @Override protected T parser(JSONObject object) throws Exception { TOAST = object.optString("message"); if (object.optInt("code") == 0) { Type[] types = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments(); return new Gson().fromJson(object.toString(), types[0]); } else if (object.optInt("code") == -200 || object.optInt("code") == -201) { BaseApplication.MYMMKV.encode("token", ""); BaseApplication.MYMMKV.encode("uid", ""); } return null; } @Override public void execute(boolean isShow) { super.execute(context,isShow); } @Override public void execute() { super.execute(context); } @Override public void execute(Context context, boolean isShow, int type, Object object) { if (!TextUtil.isNull(BaseApplication.MYMMKV.decodeString("token", ""))) { header("token", BaseApplication.MYMMKV.decodeString("token", "")); } super.execute(context, isShow, type, object); } } 在这个里面怎么获取我给后台接口传的值
最新发布
07-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值