首页 > 解决方案 > 我如何按特定顺序序列化 java 对象

问题描述

序列化到前端时,我需要按指定顺序设置此 DTO 对象。我尝试过@JsonPropertyOrder,例如:

@JsonPropertyOrder({"Body and Frame","Exterior Details","Interior Details",})
public class CertificateTabbings implements Serializable{

@SerializedName("Body and Frame")
private UsedcarInspectionCommonDto usedCarBodyAndFrame;

@SerializedName("Exterior Details")
private UsedcarInspectionCommonDto exteriorDetails;

@SerializedName("Interior Details")
private UsedcarInspectionCommonDto interiorDetails;
//getters //setters}

后来我正在为这些对象设置值,例如:

UsedCarInspectionReport inspectionReport = new UsedCarInspectionReport();
certificateTabbing.setUsedCarBodyAndFrame(certificationDetails.getUsedCarBodyAndFrame());
certificateTabbing.setExteriorDetails(certificationDetails.getExteriorDetails());
certificateTabbing.setInteriorDetails(certificationDetails.getInteriorDetails());

inspectionReport.setCertificateTabbings(certificateTabbing);

使用 @JsonPropertyOrder 对我不起作用。任何建议我应该如何在输出 json 中获得指定的顺序。

标签: javajsonserializationjackson

解决方案


@JsonPropertyOrder 是 Jackson 库的一部分,而 @SerializedName 是 GSON 库的一部分。GSON 不支持 json 顺序,所以为了使它工作,改变

@SerializedName

@JsonProperty

注意:任何适当的前端框架都应该无序处理 json,因为http://json.org

对象是一组无序的名称/值对。

所以订购 json 对象可能是不必要的。


推荐阅读