Reputation: 89
Is there a simple way to deserialize a list of strings into a single string?
For example, I would have this JSON:
{
"stringList": [
"somethingElse"
],
"simpleString": "something",
}
I would like it to be deserialized into this POJO:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class AClass {
@JsonProperty("stringList")
private String justAString;
@JsonProperty("simpleString")
private String someString;
}
I would like to mention that it is certain that the list has only one item and have no control over how it is generated. Is the only way to go a custom deserializer for the justAString field?
EDIT I would like to use ObjectMapper class from Jackson if it is possible
Upvotes: 0
Views: 2749
Reputation: 159086
One way is to use alternate getter/setter methods for the property that needs conversion, i.e. move the @JsonProperty
annotations from the fields to the getter methods, add an extra set of getter/setter methods, and use @JsonIgnore
so the ObjectMapper
doesn't use them:
class AClass {
private String justAString;
private String someString;
@JsonProperty // JSON field named same as virtual property
private List<String> getStringList() { // Getter for virtual property (private = hidden from Java callers)
return Collections.singletonList(this.justAString);
}
private void setStringList(List<String> stringList) { // Setter for virtual property
this.justAString = stringList.toString();
}
@JsonIgnore // This POJO property is not a JSON field
public String getJustAString() { // Standard POJO getter
return this.justAString;
}
public void setJustAString(String justAString) { // Standard POJO setter
this.justAString = justAString;
}
@JsonProperty("simpleString") // JSON field named different from POJO property
public String getSomeString() { // Standard POJO getter
return this.someString;
}
public void setSomeString(String someString) { // Standard POJO setter
this.someString = someString;
}
}
Test
String input = "{\r\n" +
" \"stringList\": [\r\n" +
" \"somethingElse\"\r\n" +
" ],\r\n" +
" \"simpleString\": \"something\"\r\n" +
"}";
AClass aClass = new ObjectMapper().readValue(input, AClass.class);
System.out.println("justAString = " + aClass.getJustAString());
System.out.println("someString = " + aClass.getSomeString());
Output
justAString = [somethingElse]
someString = something
Upvotes: 3
Reputation: 48258
this :
@JsonProperty("stringList")
private String justAString;
should be a list of strings dont you think??
@JsonProperty("stringList")
private List<String> justAString;
Upvotes: 0