Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 788
Diego Sanz Avatar asked Dec 14 '22 11:12

Diego Sanz


2 Answers

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;
like image 115
Deadpool Avatar answered Jan 22 '23 01:01

Deadpool


Elaborating on @Deadpool answer, you can use setter which accept the array and then join it to string:

@JsonProperty("full_name")
@JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
void setFullName(String[] name)
{
    this.fullName = String.join(",", name);
}
like image 25
matanper Avatar answered Jan 22 '23 03:01

matanper