为什么Json要求Junit测试没有参数构造器?

rwqw0loc  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(192)

我使用Jackson来示例化JSON字符串时遇到问题。我得到错误:com.fasterxml.jackson.databind.JsonMappingException:No suitable constructor found for type [simple type,class RatingDMO]:cannot instantiate from JSON object(need to add/enable type information?)
我有Map到JSON文件的字段和参数,它可以作为属性,并具有相同的类型。

注意:-如果我提供了no-arg构造函数(只是为了检查它是否工作),则Test工作。

我不能在我的代码中提供/保留默认构造函数,因为我在模型中只有很少的final字段。
mapper.readValue(new File(“ratingRequest.json”),RatingDMO.class);

POJO Class:

public class RatingDMO implements Serializable {
    
    private static final long serialVersionUID = -433016040176969496L;
    private String company;
    private String state;
    private String lob;
    private String channel;
    private String username;
    private String password;
    private String policyNumber;
    private long policyKey;
    private String transactionType;
    private String evaluationType;
    private String clientID;
    private String policyTerm;
    private String effectiveDate;
    private String policyXML;
    private String webXML;
    private String firstName;
    private String lastName;
    private String businessName;
    private String city;
    private String zip;
    private String effectiveDtStart;
    private String effectiveDtEnd;
    private String searchType;
    private String uuid;
    private List<String> policyStatusCodes;
    private Map<String,String> eAdvisorCoverages;
    private Map<String,String> customCoverages;
    private Map<String,String> defaultCoverages;
    private String action;
    private String type;
    private String selectedCoverage;
    private boolean motorClubMember;
    private String selectedSubCoveres;
    private boolean customRated;
    private final PolicyDMO policyDMO;
    private final String allInsuredInd;
    private final String medicareMediaidInd;
    private final boolean driversGreaterthan65;
         
    public PolicyRatingRequestDMO(PolicyDMO policyDMO, String allInsuredInd, String medicareMediaidInd, boolean driversGreaterthan65){
        this.policyDMO = policyDMO;
        this.allInsuredInd = allInsuredInd;
        this.medicareMediaidInd = medicareMediaidInd;
        this.driversGreaterthan65 = driversGreaterthan65;
    }
... }

字符串

z31licg0

z31licg01#

默认情况下,Jackson的数据绑定将尝试使用无参数构造函数构造对象,然后从JSON的相应位填充对象的属性。

@JsonCreator
public PolicyRatingRequestDMO(@JsonProperty("policyInfo") PolicyDMO policyDMO,
         @JsonProperty("allInsuredInd") String allInsuredInd,
         @JsonProperty("medicareMediaidInd") String medicareMediaidInd,
         @JsonProperty("driversGreaterThan65") boolean driversGreaterthan65){
    this.policyDMO = policyDMO;
    this.allInsuredInd = allInsuredInd;
    this.medicareMediaidInd = medicareMediaidInd;
    this.driversGreaterthan65 = driversGreaterthan65;
}

字符串
JsonCreator annotation告诉Jackson要调用哪个构造函数,它的参数用JsonProperty注解,以指示JSON中的哪些属性对应于构造函数中的哪些参数。JSON中与构造函数参数不对应的其他属性将通过setter或直接字段访问正常注入。

相关问题