0

I have the following Json string:

String jsonString = "[
  {
    "nameOnCard": "Test T",
    "active": true,
    "declineReason": null
  },
  {
    "nameOnCard": "TestT",
    "active": false,
    "declineReason": "payment_stolen"
  }
]";

The string is contained in an object called ApiResponse in a field called data. E.g.

APIResponse apiResponse = APIResponse.builder()
                .data(jsonString)
                .build();

I am trying to map the contents of the string into a list of PaymentObject. The payment object looks like this:

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PaymentObject {

    private String declineReason;
    private String nameOnCard;
    private String active; 
}

I am using the following to convert the String into a List<PaymentObject> by the following:

List<PaymentObject> paymentObjectDTOs = mapper.convertValue(apiResponse.getData(), new TypeReference<>() {});

where mapper is ObjectMapper from Jackson 2.13.2.2.

But I am getting the following error:

Cannot deserialize value of type `java.util.ArrayList<com.abc.PaymentObject>` from String value (token `JsonToken.VALUE_STRING`)
 at [Source: UNKNOWN; byte offset: #UNKNOWN]

I can't see what's going wrong.

1 Answer 1

1

You're missing the referenced type. This will work:

List<PaymentObject> paymentObjectDTOs =mapper.readValue(apiResponse.getData(), new TypeReference<List<PaymentObject>>(){});

But make sure you've all the getters and setters methods on the PaymentObject class, as well as the default constructor.

Sign up to request clarification or add additional context in comments.

1 Comment

The generic type parameters can be inferred from the type on the left-hand side, but your answer works because you're using the correct method, readValue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.