I am trying to convert a java object into a a List of Object. My current object is the ff.
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class)
public final class GetCreditCardInfo {
@JsonAlias("ns:return")
private List<CreditCardDetails> details;
@JsonAlias("ns:return")
private CreditCardDetails detailsObject;
}
What the code does above is get the object or list of objects in the response. I plan on just converting an object into a List of objects if the details variable doesnt have a value at all.
I'm doing this since our southbound APIs throw either an Object or a List of Objects seen below.
For the existing implementation that I have, I just want to just convert the object into a List so that if the API threw an Object response. My existing implementation for a List of Object would still work since the api that threw an object will still be read as a single List of object in my API. Is there a way to convert my Object to List of Objects?
CodePudding user response:
tl;dr
List.of( myCreditCardDetails )
List.of
Java 9 and later provides several handy List.of
methods on the List
interface for instantiating an unmodifiable list.
To make an unmodifiable list containing a single object:
List< CreditCardDetails > list = List.of( myCreditCardDetails ) ;
To make an empty unmodifiable list:
List< CreditCardDetails > list = List.of() ;
To make an unmodifiable list containing multiple objects:
List< CreditCardDetails > list = List.of( aliceCreditCardDetails , bobCreditCardDetails , carolCreditCardDetails , davisCreditCardDetails ) ;
To make an unmodifiable list copied from a modifiable list, call List.copyOf
.
List< CreditCardDetails > list = List.copyOf( otherModifiableList ) ;