我在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");
}
}
造成这种奇怪编码的原因是什么?
如何修改代码以避免此类问题?
答案 0 :(得分:0)
找到解决方案。似乎旧版本将成本片段解释为字符串而不是JSONObject。这样做似乎解决了这个问题:
ticketObject.remove("cost");
ticketObject.put("cost", new JSONObject(getCost()));