JSONObject 创建抛出空指针异常
Posted
技术标签:
【中文标题】JSONObject 创建抛出空指针异常【英文标题】:JSONObject Creation throwing Null Pointer Exception 【发布时间】:2016-12-24 14:01:58 【问题描述】:我在 android Studio 中,我正在尝试创建一个可以进行网络连接的 Android 应用。我可以获得一些 JSON 数据,但是每当我将获得的字符串转换为 JSONObject
时,就会抛出 NullPointerException
。这是我的日志错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at com.daita.getdusa.GetDataTask.doInBackground(GetDataTask.java:58)
at com.daita.getdusa.GetDataTask.doInBackground(GetDataTask.java:21)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
导致异常的代码行是这样的:
JSONObject object = new JSONObject(result);
编辑
我被要求放更多源代码,所以这里是(AsyncTask)
public class GetDataTask extends AsyncTask<Void, Void, String>
TextView submitView;
public GetDataTask(TextView submitView)
this.submitView = submitView;
@Override
protected void onPreExecute()
super.onPreExecute();
submitView.setText("Loading...");
@Override
protected void onPostExecute(String s)
super.onPostExecute(s);
submitView.setText(s);
@Override
protected String doInBackground(Void... voids)
String result;
result = getJSON("http://api.datausa.io/attrs/geo/");
JSONArray data;
List<String> parsedData = null;
List<String> geoID = new ArrayList<>();
try
JSONObject jsonObject = new JSONObject(result);
data = jsonObject.getJSONArray("data");
parsedData = new ArrayList<>();
Log.i("DUSA", String.valueOf(jsonObject.length()));
for(int i=0; i < data.length(); i++)
parsedData.add(data.getString(i));
for(String string: parsedData)
//8, 9
String[] dta = string.split(",");
String populationResult = getJSON("http://api.datausa.io/api/?show=geo&sumlevel=all&required=pop&year=latest&geo="+dta[9].substring(1, dta[9].length()-1));
if (result != null && result != "\"error\": \"No tables can match the specified query.\"")
JSONObject popObject = new JSONObject(populationResult);
JSONArray popData = popObject.getJSONArray("data");
String section = popData.getString(0);
geoID.add(dta[8] + "," + dta[9] + "," + section);
else
geoID.add(dta[8] + "," + dta[9] + ", null");
catch (JSONException e)
e.printStackTrace();
return geoID.toString();
public String getJSON(String url)
HttpURLConnection c = null;
try
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.connect();
int status = c.getResponseCode();
switch (status)
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
sb.append(line+"\n");
br.close();
return sb.toString();
catch (Exception ex)
return ex.toString();
finally
if (c != null)
try
c.disconnect();
catch (Exception ex)
return null;
注意:如果您想要实时源代码更新,请查看这些文件https://www.dropbox.com/sh/5852rt2rakk6iii/AAAgjsqOTsFfP1N4kS1KzuTBa?dl=0
【问题讨论】:
能否添加代码和字符串。 只需添加一个空检查器。那应该很好。还要确保你实际上得到了任何结果。同时添加结果代码。 空检查器不起作用。 @PritamBanerjee 你能说得更具体点吗? @苏曼达斯 你有线程问题,你想使用尚未获取的 JSON 对象 【参考方案1】:试图为你做这一切,但让我一步一步为你简化:
package com.daita.getdusa;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by User on 8/12/2016.
*/
public class GetDataTask extends AsyncTask<String, Void, Void>
// Put in Main never here.
String result;
String allValues;
Context context;
public GetDataTask(Context mContext)
this.context = mContext;
@Override
protected void onPreExecute()
super.onPreExecute();
((TextView)((MainActivity)context).findViewById(R.id.resultView)).setText("Loading...");
@Override
protected void onPostExecute(Void aVoid)
super.onPostExecute(aVoid);
((TextView)((MainActivity)context).findViewById(R.id.resultView)).setText(result);
@Override
protected Void doInBackground(String... strings)
HttpURLConnection c = null;
try
URL u = new URL("http://api.datausa.io/attrs/geo/"); // use urls first value
c = (HttpURLConnection) u.openConnection();
int status = c.getResponseCode();
switch (status)
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
sb.append(line + "\n");
br.close();
result = sb.toString();
getValue();
catch (Exception ex)
ex.printStackTrace();
finally
if (c != null)
try
c.disconnect();
catch (Exception ex)
return null;
public void getValue()
// FIX IT
// Parse the JSON properly
现在了解json解析,数据量很大,需要以更小的格式响应这个巨大的json,甚至崩溃在线json格式化程序。 :)
此代码用于显示所有 json。希望这会有所帮助。
【讨论】:
我试过你的方法,还是不行。你认为我应该在 onPostExecute 中完成所有 JSONObject 解析工作吗?对不起,如果我给你带来任何麻烦。 @苏曼达斯 不是问题,是的,您可以在那里完成。试着把代码放在github上让我检查一下,看看是什么问题。 在 GitHub 中创建它时遇到问题,但我在 Dropbox 中创建了一个链接:dropbox.com/sh/5852rt2rakk6iii/AAAgjsqOTsFfP1N4kS1KzuTBa?dl=0@sumandas 在异步任务、连接等方面发现了多个问题。将上传基础知识..并添加详细信息以回答,但您必须自己修复 JSON :( 当 HttpURLConnection 失败时,这仍然会导致相同的 NPE。【参考方案2】: public class Test
static String Json="'root':['ratedetails':['levelOne':["+ "'FGROUP':'A','rentalpackage':'2D','NOOFDAYS':'2', 'HOURS':'0', 'PERIODPRICE':'100.00',"+ "'CUSTOMERPERDAY':'50.00', 'DRIVERPERDAY':'50.00' ,'KMALLOWANCE':'2', 'EXTKMALLOWPDAY':'60',"+ "'DRIVERKMCHARGE':'5', 'CUSTOMERKMCHARGE':'3', 'MAXIMUMKMCHARGE':'99999999', 'MAXKMCHRGTYPE':'0'"+",'HIDDEN':'2',"+ "'FGROUP':'A','rentalpackage':'2D','NOOFDAYS':'2', 'HOURS':'0', 'PERIODPRICE':'100.00',"+ "'CUSTOMERPERDAY':'50.00', 'DRIVERPERDAY':'50.00','KMALLOWANCE':'2', 'EXTKMALLOWPDAY':'60',"+ "'DRIVERKMCHARGE':'5', 'CUSTOMERKMCHARGE':'3', 'MAXIMUMKMCHARGE':'99999999', 'MAXKMCHRGTYPE':'0'"+",'HIDDEN':'2'"+ "]"+ "]"+ "]";
public static void main(String[] args)
//new Test().main();
String s[]=Json.split(",");
for(int i=0;i<s.length;i++)
if(true)
System.out.println(s[i].split(":")[s[i].split(":").length-2].substring(s[i].split(":")[s[i].split(":").length-2].indexOf("'")+1, s[i].split(":")[s[i].split(":").length-2].lastIndexOf("'"))+" "+ s[i].split(":")[s[i].split(":").length-1].substring(s[i].split(":")[s[i].split(":").length-1].indexOf("'")+1, s[i].split(":")[s[i].split(":").length-1].lastIndexOf("'")));
else
System.out.println(s[i].split(":")[0].replace("'", "").trim()+" "+s[i].split(":")[1].replace("'", "").trim()); // System.out.println(Json.split(",")[5].split(":")[1].replace("'", ""));
【讨论】:
以上是关于JSONObject 创建抛出空指针异常的主要内容,如果未能解决你的问题,请参考以下文章