[英]Cannot receive utf-8 characters by json to Android
I'm building a simple Android application that sends items by json to a python web service for storage in a sqlite database. 我正在构建一个简单的Android应用程序,该应用程序通过json将项目发送到python网络服务以存储在sqlite数据库中。 This part works fine and when recalled the items have their correct 'åäö' characters.
此部分工作正常,并且在召回时,这些项目均带有正确的“åäö”字符。
When I put these items in a json to return to the application (using code below) I'm not so sure any more. 当我将这些项目放在json中以返回到应用程序时(使用下面的代码),我不确定。 Instead of 'ö' I get '\\xc3\\xb6', which I believe would be the utf-8 representation?
取而代之的是'\\ xc3 \\ xb6',而不是'ö',我相信它将是utf-8表示形式?
connection = sqlite3.connect('database.db')
connection.text_factory = str
cursor = connection.cursor()
cursor.execute("SELECT item, number FROM Items")
rows = cursor.fetchall()
jsobj = []
for row in rows:
jsobj.append({'number':row[1], 'item':row[0]})
When I parse the json object in my app I'm not able to turn the '\\xc3\\xb6' back into 'ö' 当我解析应用程序中的json对象时,我无法将'\\ xc3 \\ xb6'变回'ö'
This is the Android code at work: 这是工作中的Android代码:
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet(super.url);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content, "UTF-8"));
JSONArray itemsOnServer = new JSONArray();
itemsOnServer = new JSONArray(reader.readLine());
return itemsOnServer;
Result sent into another function: 结果发送到另一个函数:
ArrayList<Vara> varor = new ArrayList<Vara>();
String vara = "";
int antal;
for (int i = 0; i < json.length(); i++) {
JSONObject object;
try {
object = json.getJSONObject(i);
try {
try {
vara = new String(object.getString("vara").getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} System.out.println(vara);
antal = object.getInt("antal");
varor.add(new Vara(vara, antal));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return varor;
Everything works fine except the special characters. 除特殊字符外,一切正常。 Please help, I'm going nuts.
请帮助,我疯了。
b'\\xc3\\xb6'
is a bytestring that can be decoded into Unicode string that contains a single U+00f6 LATIN SMALL LETTER O WITH DIAERESIS
Unicode codepoint : b'\\xc3\\xb6'
是一个字节字符串,可以将其解码为包含单个U+00f6 LATIN SMALL LETTER O WITH DIAERESIS
Unicode代码点的U+00f6 LATIN SMALL LETTER O WITH DIAERESIS
字母U+00f6 LATIN SMALL LETTER O WITH DIAERESIS
Unicode字符串:
>>> b'\xc3\xb6'.decode('utf-8')
u'\xf6'
By default text_factory
is set to unicode
for sqlite3
ie, you should receive Unicode string for TEXT
objects if you remove connection.text_factory = str
from your code. 默认情况下,将
sqlite3
text_factory
设置为unicode
,即,如果从代码中删除connection.text_factory = str
,则应该收到TEXT
对象的Unicode字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.