【发布时间】:2018-05-25 17:18:45
【问题描述】:
我有这个列表视图,我从字符串中的 json 填充它,它工作得很好,但是当这个 json 包含空格时,onclick 事件应用程序崩溃:
(我已经用一些代码和图像评论了应用程序崩溃的地方)
final ListView mylist = (ListView) findViewById(R.id.listView1);
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
JSONObject jObj = null;
String s = testopass;
int counter = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ':') {
counter++;
}
}
if (counter > 0) {
try {
try {
jObj = new JSONObject(testopass);
} catch (JSONException e) {
e.printStackTrace();
}
Iterator<String> iter = jObj.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = jObj.get(key);
Map<String, String> datum = new HashMap<String, String>(2);
datum.put("nome",value.toString());
datum.put("cf", key.toString());
data.add(datum);
} catch (JSONException e) {
// Something went wrong!
}
}
} catch (Exception er) {
}
adapter = new SimpleAdapter(getApplicationContext(), data,
android.R.layout.simple_list_item_2,
new String[]{"nome", "cf"},
new int[]{android.R.id.text1,
android.R.id.text2});
mylist.setAdapter(adapter);
mylist.setClickable(true);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = mylist.getItemAtPosition(position);
JSONObject jObj = null;
try {
jObj = new JSONObject(o.toString()); //this return error and go to catch
} catch (JSONException e) {
e.printStackTrace();
}
String cane = "";
try {
cane = jObj.getString("cf"); //crash is here because jObj is empty
} catch (JSONException e) {
e.printStackTrace();
}
}
});
testopass is a string: `{"12345674":"SPACE CRASH"}`
应用中的结果是:
我已经停止了代码:
崩溃是:
org.json.JSONException: Unterminated object at character 13 of {nome=SPACE CRASH, cf=12345674}
如何解决这个问题?我在 android 开发中非常新
我有一个部分解决方案
jObj = new JSONObject(o.toString().replace("nome=","nome=\"").replace(",","\","));
这段代码不会崩溃,但我认为有更好的解决方案?
【问题讨论】:
-
您可以使用 GSON (github.com/google/gson) 来解析 JSON。这将使您的工作更轻松
-
问题可能出在这里 datum.put("cf", key.toString());由于没有正确放置数据,因此当您尝试将其传递到下方以将其传递给 cane 时,您没有获得该值,因此 cane 为空