简体   繁体   中英

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

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;

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);
}

Both answers are great. I just want to mention about custom Deserializer.

You can easily extend from StdDeserializer<Document> and override deserialize method:

public class DocumentDeserializer extends StdDeserializer<Document> {

    @Override
    public Document deserialize(JsonParser p, DeserializationContext ctxt, Document value) throws IOException {

        JsonNode root = p.getCodec().readTree(p);
        JsonNode node = root.get("full_name");
        if(node.isArray()) {
            //get array data from node iterator then join as String and 
            //call setFirstName
        }
        return value;
    }
}

Then don't forget to call registerModule of ObjectMapper to register your deserializer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM