gpt4 book ai didi

Android - 将 JSON 转换为 UTF-8

转载 作者:行者123 更新时间:2023-11-29 01:54:00 25 4
gpt4 key购买 nike

我需要帮助将 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

最佳答案

根据 RFC 4627 JSON 的默认编码应该是 UTF-8。和 UTF-8 doesn't need a BOM这实际上是不鼓励的(严格来说:“UTF-8 既不需要也不推荐使用 BOM”)!

所以您应该做的是将您的文件保存为“UTF-8(无 BOM)”(这实际上应该是默认选项,“UTF-8(带 BOM)”应该是特殊选项。

如果您正在使用 JSONParserfrom this blog post (或类似的东西),那么你应该修复该代码:它对 ISO-8859-1 编码进行硬编码,这是错误的(除非你明确知道你需要那个)。

理想情况下,您应该遵守服务器在 HTTP header 中告诉您的编码。或者,您可以采用指定的默认值(即 UTF-8)。

关于Android - 将 JSON 转换为 UTF-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16324956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com