Minor JSON encoding issue on Android 4.1.2

I have a problem on Android 4.1.2, where the JSON object provided to us by our REST API will be weirdly encoded when submitted.

This is the json snippet I get:

"cost":{
    "amount": 0,
    "currency": "GBP"
}

I want to pretty much just pass this snippet back the same way (by modifying the other parts of json), but this is what I get on Android 4.1.2:

"cost":"{amount=0, currency=GBP}"

I believe this function calls this weird encoding:

        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;
        }

This is the addApplicationIformationToJSONObject function:

/**
 * 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");
    }
}

What causes this weird encoding?

How can I change the code to avoid such problems?

+4
source share
1 answer

. , , JSONObject. , , :

ticketObject.remove("cost");
ticketObject.put("cost", new JSONObject(getCost()));
0

Source: https://habr.com/ru/post/1568361/


All Articles