我正在构建一个简单的Android应用程序,它通过json将项目发送到python Web服务以存储在sqlite数据库中。这部分工作正常,当被召回时,这些项目有正确的'åäö'字符。
当我将这些项目放在json中以返回应用程序时(使用下面的代码)我不再那么肯定了。而不是'ö'我得到'\ 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]})
当我在我的应用程序中解析json对象时,我无法将'\ xc3 \ xb6'转回'ö'
这是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;
结果发送到另一个函数:
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;
除特殊字符外,一切正常。请帮忙,我疯了。
答案 0 :(得分:0)
b'\xc3\xb6'
是一个字节串,可以解码为包含单个U+00f6 LATIN SMALL LETTER O WITH DIAERESIS
Unicode codepoint的Unicode字符串:
>>> b'\xc3\xb6'.decode('utf-8')
u'\xf6'
默认情况下text_factory
is set to unicode
for sqlite3
,如果您从代码中删除TEXT
,则应收到connection.text_factory = str
个对象的Unicode字符串。