简体   繁体   English

Jackson jsonproperty name 当有相同的多个实例时 object

[英]Jackson jsonproperty name when there are multiple instances of the same object

Take this example:举个例子:

class Car {
    Door leftDoor;
    Door rightDoor;

    Door getLeftDoor();
    Door getRightDoor();
}

class Door {
    String getType();
}

The goal is to have this json:目标是拥有这个 json:

{
    "Door.lefttype": "A",
    "Door.righttype": "B"
}

I have the object mapper configured that only things with @JsonProperty are converted to Json.我将 object 映射器配置为仅将带有 @JsonProperty 的内容转换为 Json。

If I only had one door, I could simply put @JsonProperty("door.type") on String getDoorType() .如果我只有一扇门,我可以简单地将@JsonProperty("door.type")放在String getDoorType()上。 But since there are multiple instances of the same type I can't put the annotation on the last class. Furthermore, I need @JsonUnwrapped because I don't want it to make a hierarchy in the json. I want this:但是由于有多个相同类型的实例,我不能将注释放在最后一个 class 上。此外,我需要 @JsonUnwrapped 因为我不希望它在 json 中创建层次结构。我想要这个:

door.lefttype: "A"

instead of代替

door: {
    lefttype: "A"
}

What I have so far (I'm using interfaces + mixins since I don't have access to the classes directly):到目前为止我所拥有的(我正在使用接口+ mixins,因为我无法直接访问这些类):

public interface CarMixin {
    @JsonProperty
    @JsonUnwrapped
    Door getLeftDoor();

    @JsonProperty
    @JsonUnwrapped
    Door getRightDoor();
}

public interface DoorMixIn {
    @JsonProperty
    String getType();
}

I need the exact names, so this doesn't suffice.我需要确切的名称,所以这还不够。 I need to use named JsonProperties我需要使用命名的 JsonProperties

I don't think I have the same understanding of mixin as you do, and I must say I'm little unclear what is the extend of your limitation in modifying existing classes, but I would think something along the following lines might help:我不认为我对 mixin 的理解和你一样,我必须说我不太清楚你在修改现有类方面的限制是什么,但我认为以下几点可能会有所帮助:

class Car {
   Door leftDoor ;
   Door rightDoor ;

   @JsonProperty("Door.lefttype")
   String leftType() {
        return leftDoor.getType() ;
   }

   @JsonProperty("Door.righttype")
   String leftType() {
        return rightDoor.getType() ;
   }
}
   

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

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