安卓4.1.2上的奇怪JSON编码问题

4

我在 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");
    }
}

是什么导致了这种奇怪的编码方式?

我该如何修改代码以避免出现这样的问题?


我最初认为这只发生在三星Galaxy S2上,但是我已经通过模拟器验证,这可以在任何Android 4.1.2上重现。 - iceydee
需要更多的问题澄清。 - Indra Kumar S
你的 addApplicationInformationToJSONObject(json) 方法是做什么用的? - agamov
@agamov 我现在已经包含了那个函数。 - iceydee
@IndraKumarS,您需要更具体的澄清吗?我已经尽力了。 - iceydee
1个回答

0
发现了一个解决方案。似乎较旧版本将那个成本片段解释为字符串而不是 JSONObject。做这个似乎可以解决问题:
ticketObject.remove("cost");
ticketObject.put("cost", new JSONObject(getCost()));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接