使用枚举类名而不是值

问题描述 投票:0回答:1

这里的新手尝试使用映射器对包含枚举的类使用 json 序列化。我发现发送的请求中使用了类名而不是枚举值。不确定我在这里错过了什么。

该字段有@JsonValue,我也尝试过 mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)

任何指示都会非常有帮助。

谢谢

代码片段:


Mapper calling code :

CDRequest CDRequest = new CDRequest();
CDIdentifier CDIdentifier = new CDIdentifier();
 CDIdentifier.setInputType(InputTypeEnum.LEGACY);
 CDRequest.setInputIdentifier(CDIdentifier);
 String c = mapper.writeValueAsString(CDRequest);
 
Target Generated code: 
 
 public class CDRequest {
  public static final String JSON_PROPERTY_INPUT_IDENTIFIER = "inputIdentifier";
  private CDIdentifier inputIdentifier;
  public CDRequest inputIdentifier(CDIdentifier inputIdentifier) {
    
    this.inputIdentifier = inputIdentifier;
    return this;
  }

  @jakarta.annotation.Nullable
  @JsonProperty(JSON_PROPERTY_INPUT_IDENTIFIER)
  @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)

  public CDIdentifier getInputIdentifier() {
    return inputIdentifier;
  }


  @JsonProperty(JSON_PROPERTY_INPUT_IDENTIFIER)
  @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
  public void setInputIdentifier(CDIdentifier inputIdentifier) {
    this.inputIdentifier = inputIdentifier;
  }

  
  @JsonIgnoreProperties(
  value = "inputType", // ignore manually set inputType, it will be automatically generated by Jackson during serialization
  allowSetters = true // allows the inputType to be set during deserialization
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "inputType", visible = true)
@JsonSubTypes({
  @JsonSubTypes.Type(value = CR.class, name = "CUSTOMER_ID"),
  @JsonSubTypes.Type(value = CN.class, name = "CUSTOMER_NUMBER"),
  @JsonSubTypes.Type(value = LCR.class, name = "LEGACY"),
  @JsonSubTypes.Type(value = CR.class, name = "CR"),
  @JsonSubTypes.Type(value = CN.class, name = "CN"),
  @JsonSubTypes.Type(value = LCR.class, name = "LCR"),
})

}


Identifier :

public class CDIdentifier {
  /**
   * Gets or Sets inputType
   */
  public enum InputTypeEnum {
    LEGACY("LEGACY");

    private String value;

    InputTypeEnum(String value) {
      this.value = value;
    }

    @JsonValue
    public String getValue() {
      return value;
    }

    @Override
    public String toString() {
      return String.valueOf(value);
    }

    @JsonCreator
    public static InputTypeEnum fromValue(String value) {
      for (InputTypeEnum b : InputTypeEnum.values()) {
        if (b.value.equals(value)) {
          return b;
        }
      }
      throw new IllegalArgumentException("Unexpected value '" + value + "'");
    }
  }

  public static final String JSON_PROPERTY_INPUT_TYPE = "inputType";
  protected InputTypeEnum inputType;

映射器返回类名“CDIdentifier”本身,而不是值“Legacy”

枚举值从mapper.writeAsStirng返回

java json spring jackson openapi
1个回答
0
投票

使用@JsonFormat注解:

@JsonFormat(shape = JsonFormat.Shape.STRING)
protected InputTypeEnum inputType;
© www.soinside.com 2019 - 2024. All rights reserved.