我在 Android 4.1.2 上遇到了一个问题,即我们的 REST API 给出的 JSON 对象在发送回来时被奇怪地编码。
这是我收到的 JSON 片段:
"cost":{
"amount": 0,
"currency": "GBP"
}
我想基本上只是将这个特定的片段以相同的方式传递回去(修改json的其他部分),但这就是我在Android 4.1.2上得到的:
"cost":"{amount=0, currency=GBP}"
我认为导致奇怪编码的函数在这里:
private StringEntity getEntityForRequest(final Payment payment, final PaymentDelegate delegate) {
JSONObject json = new JSONObject();
MyApplication.getContext().addApplicationInformationToJSONObject(json);
StringEntity entity = null;
try {
entity = new StringEntity(json.toString(), "UTF-8");
} catch (UnsupportedEncodingException e1) {
payment.markAsFailed("Reservation failed, data returned not expected.");
save(payment);
if (delegate != null) {
delegate.onFailure(new MyError(MyError.DEFAULT_STATUS, MyError.DEFAULT_TYPE, "Payment error", "Error during reservation"));
}
}
return entity;
}
这是addApplicationIformationToJSONObject函数:
/**
* Adds system information to a JSON object.
*/
public void addApplicationInformationToJSONObject(JSONObject json) {
try {
try {
json.put("app_version", getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
} catch (NameNotFoundException e) {
json.put("app_version", "Unknown");
}
json.put("device", getDeviceName());
json.put("os_type", "android");
json.put("os_version", String.format("%d", Build.VERSION.SDK_INT));
json.put("device_id", Secure.getString(getContext().getContentResolver(), Secure.ANDROID_ID));
} catch (JSONException e) {
MyLog.e("MyApplication", "Error when adding system information to JSON");
}
}
是什么导致了这种奇怪的编码方式?
我该如何修改代码以避免出现这样的问题?
addApplicationInformationToJSONObject(json)
方法是做什么用的? - agamov