How to parse field that may be a string and may be an array with Jackson

Diego Sanz :

I'm new with java and objectMapper. I'm trying to parse json field that is possible that a key have two types, it could be a string or array.

examples:

{
  "addresses": [],
  "full_name": [
    "test name_1",
    "test name_2"
  ],
}

or

{
{
  "addresses": [],
  "full_name": "test name_3",
}
}

Class example:


@JsonIgnoreProperties(ignoreUnknown = true)
@Data -> lombok.Data
public class Document {

    private List<String> addresses;

    @JsonProperty("full_name")
    private String fullName;
}

I used objectMapper to deserialize json, works correctly when the 'full_name' field has a string but when arrive an array fail deserialization.

The idea is that when arrive a string put value in attribute but when arrive array, concatenate de array elements as string (String.join(",", value))

It's possible to apply custom deserialization in a class method? For example setFullName() (use lombok.Data)

I saw others examples in this site, but not work.

Thank's for all

Deadpool :

From jackson 2.6 you can use JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY

@JsonProperty("full_name")
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
private String[] fullName;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86157&siteId=1
May