0

If my property name has dot in json as shown in below, payment_details.type and if I want to retrieve Json value using Gson, how and what I will have to do.

{
    "statusCode": 422,
    "error": "Unprocessable Entity",
    "message": "Bad data received",
    "err_data": {
        "payment_details.type": {
            "location": "body",
            "param": "payment_details.type",
            "msg": "Must be either etransfer or cheque"
        }
    }
}

Currently I am doing this..

new Gson().fromJson(response.asString(), MyApiResponse.class).getErr_data().getPayment_details_type().getMsg();

It doesn't work for me.. I can't retrieve "msg" value from above json.

James Z
  • 12,209
  • 10
  • 24
  • 44
Paresh
  • 1,140
  • 2
  • 12
  • 29

1 Answers1

1

Annotate the field with @SerializedName to indicate the property name for the JSON serialization.

It will be something like:

public class MyApiResponse {

    @SerializedName("err_data")
    private ErrorDetails errorDetails;

    ...
}
public class ErrorDetails {

    @SerializedName("payment_details.type")
    private PaymentDetails paymentDetails;

    ...
}
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • 1
    Thank you very much for your quick reply. I will take a look and also will try it out. – Paresh Mar 08 '18 at 17:24
  • So if field name is not same as method name, we should Annotate the field @SerializedName, and if not Annotated then field name should match with the set/get method name? Is my understanding correct? – Paresh Mar 08 '18 at 17:29
  • @OverrockSTAR [Gson uses the fields for serialization](https://stackoverflow.com/q/6203487/1426227) and you can customize the property names with `@SerializedName`. – cassiomolin Mar 08 '18 at 17:31
  • OK. but in other case, I didn't have @SerializedName, and was using only getter method to read value and it was working fine.. for e.g. this one - `new Gson().fromJson(response.asString(), MyApiResponse.class).getErr_data().getEmail().getMsg();` - was it working because property name in json was matching with field name? – Paresh Mar 08 '18 at 17:46
  • 1
    @OverrockSTAR _"Was it working because property name in json was matching with field name"_ Yes, you got the idea. – cassiomolin Mar 09 '18 at 09:16
  • If I want to use Jackon how would I do it? – Paresh Mar 09 '18 at 13:23
  • @OverrockSTAR You would use `@JsonProperty` instead. – cassiomolin Mar 09 '18 at 13:26
  • I got it. Thank you! – Paresh Mar 09 '18 at 13:33