Android JSONObject始终返回"null";

编程入门 行业动态 更新时间:2024-10-24 17:30:49
本文介绍了Android JSONObject始终返回"null";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从Web服务器解析JSON.提取数据不是问题,但是当我尝试创建JSONObject时,它总是返回null.

I'm trying to parse JSON from my web server. Fetching data isn't the problem but when I try to create a JSONObject it always returns null.

我的JSON:

{"apikey":"c34750f19843vo45239o","error":false}

还有我的Java:

private class GetJSON extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... arg0) { JSONResult = null; HttpHandler sh = new HttpHandler(); sh.HTTPMethod = DefaultMethod; // Making a request to url and getting response String jsonStr = sh.makeServiceCall(ApiUrl+tmpUrl); System.out.println("Response from "+ApiUrl+tmpUrl+": " + jsonStr); if (jsonStr != null) { try { JSONResult = new JSONObject(jsonStr); } catch (final JSONException e) { System.out.println("Json parsing error: " + e.getMessage()); } } else { System.out.println("Couldn't get json from server."); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); clearRequest(); } }

我尝试使用jsonStr.toString(),但结果相同.我也可以用Java记录我的JSON字符串,但无法解析.

I have tried with jsonStr.toString() but same result. I can also log my JSON string in Java but it isn't parsed.

这是它返回null的地方:

if(JSONResult != null && JSONResult.has("apikey")) { ApiKey = JSONResult.getString("apikey"); System.out.println("Successfully got ApiKey: "+ApiKey); }else{ if(JSONResult == null){System.out.println("Is Null");} }

对不起,我的英语不好.希望你能理解:)

Sorry for my bad English. Hope you understand :)

推荐答案

仅凭猜测,因为您的代码显示不足.

Just guessing, since you did not show enough of your code.

您很有可能在收到结果之前先对其进行检查. AsyncTask与您的主线程异步运行,您必须等到它完成后才能使用结果.

Most likely you check the result before it has been received. The AsyncTask runs asynchronously to your main thread and you would have to wait until it is finished before you can use the result.

实际上,这就是为什么存在onPostExecute方法的原因.这是处理结果的正确位置.

In fact, that's the reason why there is an onPostExecute method. This is the correct place to process the result.

更多推荐

Android JSONObject始终返回"null";

本文发布于:2023-11-14 19:14:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588304.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JSONObject   Android   null   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!