简体   繁体   English

具有相同 JsonProperty 属性的不同字段

[英]Different fields with same JsonProperty attribute

Is it possible to have something like below while serializing a JSON in the same class在同一个 class 中序列化 JSON 时是否可能有类似下面的内容

@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.所以我可以在形成 json 时只包含 statsDetails 或 statsDetailsList 中的一个。

I also have a separate JsonMapper code that transforms this pojo data into a json which i haven't included here.我还有一个单独的 JsonMapper 代码,可以将这个 pojo 数据转换为 json,我没有在这里包含。

You cannot do that.你不能这样做。 It will throw JsonMappingException jackson cannot know which of the fields are you referring to.它将抛出JsonMappingException jackson 无法知道您指的是哪个字段。 You can try it by yourself with the following code:您可以使用以下代码自行尝试:

POJOClass: POJO类:

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:主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: output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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