简体   繁体   中英

Different fields with same JsonProperty attribute

Is it possible to have something like below while serializing a JSON in the same class

@JsonProperty("stats")
private StatsDetails statsDetails

@JsonProperty("stats")
private List<StatsDetails> statsDetailsList

so i can have either statsDetails or statsDetailsList only one of these being included while forming a json.

I also have a separate JsonMapper code that transforms this pojo data into a json which i haven't included here.

You cannot do that. It will throw JsonMappingException jackson cannot know which of the fields are you referring to. You can try it by yourself with the following code:

POJOClass:

import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSetter;

import java.util.List;

public class POJOClass {

    public POJOClass(String object) {
        this.object = object;
    }

    public POJOClass(List<String> objectList) {
        this.objectList = objectList;
    }

    @JsonProperty("object")
    public String object;

    @JsonProperty("object")
    public List<String> objectList;
    @JsonGetter("object")
    public String getObject() {
        return object;
    }

    @JsonGetter("object")
    public List<String> getObjectList() {
        return objectList;
    }

    @JsonSetter("object")
    public void setObject(String object) {
        this.object = object;
    }

    @JsonSetter("object")
    public void setObjectList(List<String> objectList) {
        this.objectList = objectList;
    }
}

Main class:

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class MainClass {

    public static void main(String[] args) {
        String text = "f";
        List<String> list = Arrays.asList("a", "b", "c");
        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(new POJOClass(text));
            String listJson = mapper.writeValueAsString(new POJOClass(list));
            System.out.println("json=" + json);
            System.out.println("listJson=" + listJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The output:

com.fasterxml.jackson.databind.JsonMappingException: Multiple fields representing property "object": POJOClass#object vs POJOClass#objectList

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