【发布时间】:2017-11-17 21:16:30
【问题描述】:
在将字符串转换为 json 对象时出现空指针错误,我尝试过 gson、parser 等,但似乎都没有工作。
有人可以为以下响应提供解决方案(我已经完成子字符串以删除“数据:”):
data: {
"C": "abc",
"A": [{
"B": "BcastHub",
"C": "onData",
"D": [{
"ID": "1",
"One": [{
"Plus": 5.0,
"Minus": 93400.0
}, {
"Plus": 4.9,
"Minus": 8570.0
}, {
"Plus": 4.8,
"Minus": 140606.0
}],
"Two": [{
"Plus": 5.1,
"Minus": 34.0
}, {
"Plus": 5.2,
"Minus": 44622.0
}, {
"Plus": 5.3,
"Minus": 2408.0
}]
}]
}]
}
我的获取代码
try{
URL urlData = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlData.openConnection().getInputStream(), "utf-8"));
String struct = reader.readLine();
while ((struct = reader.readLine()) != null ) {
if(!struct.equals("")) {
struct = struct.substring(6,struct.length());
JSONParser parser = new JSONParser();
JSONObject lev1 =(JSONObject) parser.parse(struct);
//JSONObject lev1 = (JSONObject) obj;
JSONObject parent = (JSONObject) lev1.get("A");
for(int j=0;j<parent.length();j++) {
JSONObject child1 = (JSONObject) parent.get("D");
JSONArray child2 = (JSONArray) child1.get("One");
for (int i = 0; i < child2.length(); i++) {
JSONObject item = child2.getJSONObject(i);
final String plus = item.getString("Plus");
final String minus = item.getString("Minus");
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText("Plus => " + plus + "Minus = > " + minus);
}
});
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
如果你还想要什么,请告诉我。谢谢。
编辑:我正在修剪字符串的开头以使其格式正确,然后将字符串转换为 JSONObject 给我错误。在 JSONObject 父 = (JSONObject) lev1.get("A");因为 lev1 为空。
【问题讨论】:
-
您的 Json 响应错误 在此处验证您的 Json 响应 jsoneditoronline.org
-
我知道我从一开始就修剪了数据,直到我在问题中提到的'{',然后将字符串转换为给我 NPE 的 json 对象。
-
给出你回复的网址,这样我可以更好地帮助你
-
嗯,出于安全原因,这是不可能的......但如果你能为这种格式提供解决方案,那么这就是数据的确切格式,那么它会很棒。
-
好的,那我去看看
标签: android arrays json parsing