Json序列化具有不同属性名称的数据

时间:2018-08-17 17:11:43

标签: java json

我有一个输入Json,如下所示:-

procedure TForm1.ProxyConnect(AContext: TIdContext);
var
  lLine: string;
begin
  lLine := fMappings[TIdMappedPortContext(AContext).Connection.IOHandler.Tag];
  TIdMappedPortContext(AContext).OutboundClient.IOHandler.WriteLn(Format('CONNECT %s HTTP/1.1',[lLine]));
  TIdMappedPortContext(AContext).OutboundClient.IOHandler.WriteLn();
  lLine := '';
  repeat
    lLine := TIdMappedPortContext(AContext).OutboundClient.IOHandler.ReadLn(#$A,fTimeOut);
  until lLine = '';
end;

我正尝试将其映射到java类,如下所示:-

{
    "stress": {
      "FxPOS": {
        "SX": [
          -14.2581,
          -15.6962,
          -12.6547,
          -13.639,
          -6.305,
          7.0567,
          15.508
        ]
      }
    }
}

映射数据并将其重新序列化为JSON之后,得到以下输出:

public class DTO implements Serializable {
        private static final long serialVersionUID = -1L;
        private Stress stress;

        @Getter
        @Setter
        @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
        public static class Stress implements Serializable {

            private static final long serialVersionUID = 5133888753296054639L;
            @JsonSerialize
            @JsonProperty("FxPOS")
            private Config fxPOS;
            }
            }



   @Getter
    @Setter
    @NoArgsConstructor
    @JsonSerialize
    @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
    public class Config implements Serializable {
        /**
         * 
         */
        private static final long serialVersionUID = -7335939612336666586L;
        @JsonSerialize
        @JsonProperty("SX")
        private String sx;
        }

有人可以告诉我我在哪里做错了吗? 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我认为您可以通过定义显式的getter和setter方法并使用@JsonGetter@JsonSetter进行注释来实现。 在这些注释中,您可以指定要反序列化的名称和要序列化的名称的名称。否则,该名称将仅来自属性名称。

例如:

public class DTO implements Serializable {
    private static final long serialVersionUID = -1L;
    private Stress stress;

    public static class Stress implements Serializable {

        private static final long serialVersionUID = 5133888753296054639L;

        private Config fxPOS;

        @JsonGetter("FxPOS")
        public Config getFxPOS() {
            return fxPOS;
        }

        @JsonSetter("FxPOS")
        public void setFxPOS(int fxPOS) {
            this.fxPOS = fxPOS;
        }
    }
}

@Getter
@Setter
@NoArgsConstructor
@JsonSerialize
public class Config implements Serializable {

    private static final long serialVersionUID = -7335939612336666586L;

    private String sx;

    @JsonGetter("SX")
    public String getSx() {
        return sx;
    }

    @JsonSetter("SX")
    public void setRed(int sx) {
        this.sx = sx;
    }
}