我需要帮助将 JSON 响应转换为 UTF-8。当我使用 UTF-8(没有 BOM)保存我的 .json 文件时,一切都运行良好。当我只使用 UTF-8 保存文件时,它不起作用,应用程序在获取 JSON 时崩溃。
底部的 Logcat
来源:
..
public class JSONPARSER extends ListActivity {
private static String url = "http://profusum.se/neger.json";
private static final String TAG_CONTACTS = "messages";
private static final String TAG_NAME = "namn";
private static final String TAG_ID = "id";
private static final String TAG_KIK = "facebook";
private static final String TAG_IMGURL = "img";
JSONArray contacts = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drivers);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try {
contacts = json.getJSONArray(TAG_CONTACTS);
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME,}, new int[] {
R.id.inboxName, });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String name = ((TextView) view.findViewById(R.id.inboxName)).getText().toString();
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
startActivity(in);
}
});
}
}
我现在已经努力寻找这个,我猜这很简单..但我无法弄清楚。
05-01 21:13:08.213: E/JSON Parser(27153): Error parsing data org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject
概括
当我在 Notepad++ 中使用“UTF-8(无 BOM)”保存文件时,解析成功。但我在应用程序中得到了这些奇怪的符号。(见示例)
但是当我在 Notepad++ 中使用“UTF-8”保存文件时,JSON 会给我正确的符号,但 Android 应用程序不会解析它。
Example
Tim Billström