Android开发遇JSONException: No value for data错误,请求排查
解决Android读取JSON时的
org.json.JSONException: No value for data错误 新年快乐!刚接触JSON开发踩点小坑很正常,我来帮你一步步排查解决~
问题核心定位
从报错日志和代码来看,抛出No value for data异常,本质是代码解析到的JSON字符串里找不到data这个键。结合你的代码,大概率是JSON文件读取不完整,再加上一些小的初始化问题导致的。
分步解决方案
1. 修复JSON文件读取逻辑
你用Scanner逐行读取的方式很容易因为换行、编码问题导致JSON字符串不完整,换成更可靠的字节流读取方式:
public void loadGrades(View view){ Resources res = getResources(); InputStream is= res.openRawResource(R.raw.test02); try { byte[] buffer = new byte[is.available()]; is.read(buffer); is.close(); // 指定UTF-8编码避免乱码 String json = new String(buffer, "UTF-8"); parseJson(json); } catch (IOException e) { e.printStackTrace(); } }
2. 初始化ArrayList避免空指针
你的list变量只声明了但没初始化,解析时调用list.add()会直接崩掉,在onCreate里补上初始化:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化存储字符的列表 list = new ArrayList<>(); }
3. 给JSON解析加容错机制
用optJSONArray替代getJSONArray,即使data不存在也不会直接抛异常,还能给用户友好提示:
private void parseJson(String s){ TextView mala = (TextView) findViewById(R.id.acc); try { JSONObject root = new JSONObject(s); // 用optJSONArray做容错,找不到data时返回null JSONArray dt = root.optJSONArray("data"); if(dt == null){ mala.setText("JSON文件中未找到data数组"); return; } int len = dt.length(); for (int i = 0; i < len; i++) { JSONObject chara = dt.getJSONObject(i); String charStr = chara.optString("character", ""); if (!charStr.isEmpty()) { list.add(charStr); } } // 根据列表长度安全设置初始文本 if(list.size() > 1){ mala.setText(list.get(1)); } else if(list.size() > 0){ mala.setText(list.get(0)); } else { mala.setText("未读取到有效字符数据"); } }catch (JSONException e){ e.printStackTrace(); mala.setText("解析JSON出错:" + e.getMessage()); } }
4. 修复第二个按钮的索引越界问题
当前currentIndex初始为0,点击后直接currentIndex++,很容易超出列表长度,加个循环判断:
public void loadGrades1(View view){ TextView txt = (TextView) findViewById(R.id.acc); if(list == null || list.isEmpty()){ txt.setText("请先点击第一个按钮加载数据"); return; } currentIndex++; // 超出列表长度就回到开头循环 if(currentIndex >= list.size()){ currentIndex = 0; } String s = list.get(currentIndex); txt.setText(s); }
额外检查项
- 确认
test02.json确实在res/raw目录下,文件名没有拼写错误(Android资源文件名不能有大写,你的test02是合规的)。 - 打开JSON文件检查语法,比如有没有遗漏逗号、引号不匹配的情况,可以直接复制内容到浏览器控制台,用
JSON.parse(你的JSON字符串)测试是否有效。
内容的提问来源于stack exchange,提问作者Smith Trigger
相关产品推荐
相关产品推荐

