根据Class设置json属性名称

时间:2016-07-13 11:08:22

标签: java json annotations jackson

我的代码类似于:

public interface Animal {}

public class Dog implements Animal {
    String tag = "ABC";
}

public class Eagel implements Animal {
    int speed = 125;
}

public class World{
    Animal animal;
}

然后狗应该产生这样的东西:

{
    "animal" : {
        "tag" : "ABC"
    }
}

问题:当动物是狗时,如何将属性“动物”重命名为“dog”,当它是eagel时,如何将“eagel”重命名?

试验: 我最好的猜测是在接口类中设置这个:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS,
              include = JsonTypeInfo.As.EXISTING_PROPERTY,
              property = "animal")
@JsonSubTypes({
    @Type(value = Dog.class, name = "dog")
    @Type(value = Eagel.class, name = "eagel")
public interface Animal {}

但是无法让它发挥作用。还尝试使用@JsonRootName for Dog和Eagel而没有任何结果。我应该使用@JsonSubTypes来实现这个目的吗?只能设法使用@JsonSubTypes添加属性,而不是更改现有属性。使用杰克逊2.7。我的json mapper也设置为:

mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);

修改:最低完整示例:

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonNaming {

    interface Animal {}

    class Dog implements Animal {
        private String tag = "ABC";

        public Dog() {}

        public String getTag() {
            return tag;
        }

        public void setTag(String tag) {
            this.tag = tag;
        }
    }

    class World {
        @JsonSubTypes(@Type(value = Dog.class, name = "dog"))
        private Animal animal;

        public World() {}

        public Animal getAnimal() {
            return animal;
        }

        public void setAnimal(Animal animal) {
            this.animal = animal;
        }
    }

    public JsonNaming() {
        World world = new World();
        world.setAnimal(new Dog());
        try {
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(world);
            System.out.println(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new JsonNaming();
    }
}

结果: {“animal”:{“tag”:“ABC”}}

目标: {“dog”:{“tag”:“ABC”}}

1 个答案:

答案 0 :(得分:0)

为什么不使用JsonObjectBuilder