为什么Json不要求Junit测试使用任何参数构造函数? [英] Why Json ask for no argument constructor for Junit test?

查看:115
本文介绍了为什么Json不要求Junit测试使用任何参数构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Jackson来反序列化JSON字符串时遇到问题.我收到错误消息:com.fasterxml.jackson.databind.JsonMappingException:没有找到适合类型[简单类型,类RatingDMO]的构造函数:无法从JSON对象实例化(需要添加/启用类型信息吗?)

I have a problem deserializing a JSON string using Jackson. I am getting Error : com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class RatingDMO]: can not instantiate from JSON object (need to add/enable type information?)

我具有映射到JSON文件的字段,并且它的参数可以作为属性使用,并且具有相同的类型.

I have the fields mapped to the JSON file and parameters to it are available as properties AND have the same type.

注意:-如果我提供了no-arg构造函数(仅用于检查其是否有效),则测试有效.

我无法在代码中提供/保留默认构造函数,因为模型中的最终字段很少.

I can't provide/leave a default constructor in my code as I have few final fields in the model.

mapper.readValue(new File("ratingRequest.json"),RatingDMO.class);

mapper.readValue(new File("ratingRequest.json"), RatingDMO.class);

JSON文件:-

{
    "company": "Test",
    "state": "NJ",
    "lob": "PA",
    "channel": "IA",
    "username": "GlobalBatchUser",
    "password": "GlobalBatchUser",
    "policyNumber": "Test",
    "policyKey": 7267,
    "transactionType": "Quote",
    "evaluationType": null,
    "clientID": null,
    "policyTerm": "6",
    "effectiveDate": "01/01/1980",
    "policyXML": null,
    "firstName": null,
    "lastName": null,
    "businessName": null,
    "city": null,
    "zip": null,
    "effectiveDtStart": "06/06/2013",
    "effectiveDtEnd": "06/06/2014",
    "searchType": "uw1",
    "uuid": null,
    "policyStatusCodes": [],
    "eAdvisorCoverages": {},
    "customCoverages": {},
    "defaultCoverages": {},
    "action": null,
    "type": null,
    "selectedCoverage": null,
    "motorClubMember": true,
    "selectedSubCoveres": null,
    "customRated": true,
    "policyDMO": {
    "policyKey": 0,
    "company": "HP",
    "state": "NJ",
    "lob": "auto",
    "channel": null,
    "addresses": [
        {
            "addressId": 0,
            "addrLine1Txt": "20 MARTIN RD",
            "addrLine2Txt": null,
            "addrLine3Txt": null,
            "addrLine4Txt": null,
            "cityName": "LIVINGSTON",
            "cityAliasName": null,
            "countyName": null,
            "countryCd": null,
            "districtCd": null,
            "houseNum": null,
            "poBoxInd": null,
            "stateCd": "NJ",
            "zip": "07039",
            "zipPlusFour": null,
            "addressType": "ADDRESS_RESIDENCE_KEY",
            "vehicleId": 0
        },
        {
            "addressId": 0,
            "addrLine1Txt": "20 MARTIN RD",
            "addrLine2Txt": null,
            "addrLine3Txt": null,
            "addrLine4Txt": null,
            "cityName": "LIVINGSTON",
            "cityAliasName": null,
            "countyName": null,
            "countryCd": null,
            "districtCd": null,
            "houseNum": null,
            "poBoxInd": null,
            "stateCd": "NJ",
            "zip": "07039",
            "zipPlusFour": null,
            "addressType": "ADDRESS_MAILING_KEY",
            "vehicleId": 0
        }
    ],
    "policyInfo": {
        "policyKey": 0,
        "mailingAddrID": 0,
        "priorAddrID": 0,
        "residentialAddrId": 0,
        "billingAddrId": 0,
        "employerAddrId": 0,
        "policyNum": "Test",
        "policyEffDt": 1371614400000,
        "policyExpDt": null,
        "companyCD": null,
        "stateCD": "NJ",
        "term": 0,
        "emailId": "KSIRIPURAPU@PLYMOUTHROCK.COM",
        "faxNum": null,
        "homePhoneNum": null,
        "workPhoneNum": null,
        "mailingAddrIsSameInd": "Y",
        "plfCD": "HIPT",
        "affinityCD": null,
        "motorClubInd": null,
        "homeownerInd": null,
        "homeInsCarrierName": null,
        "empOrRetEduInstInd": null,
        "residenceInsTypeCD": null,
        "policyCancelledWithin3YRSIND": null,
        "declineEmailInd": null,
        "militaryServiceInd": null,
        "clueORDInd": null,
        "otherInsuranceBasicOrSpecialInd": null,
        "healthInsuranceCarrierName": null,
        "healthInsurancePolicyNumber": null,
        "transactionProgress": "1",
        "numOfAccidentInLoanedVehicle": null,
        "allInsuredInd": null,
        "medicareMediaidInd": null,
        "uwCompanyCd": null,
        "policyIssueNo": null,
        "associatedEduAffilatedOrgInd": null,
        "eDocumentsInd": null
    },
    "eligibility": [],
    "policyAgency": {
        "policyKey": 0,
        "branchID": null,
        "agencyID": null,
        "producerId": null,
        "agencyHierId": 23155,
        "agentLoginId": null,
        "userName": null,
        "userTypeCd": null,
        "emailAddressId": null,
        "referChannel": "Others"
    },
    "participants": [
        {
            "policyKey": 0,
            "participantId": 0,
            "firstName": "KHAGENDRA",
            "middleName": null,
            "lastName": "SIRIPURAPU",
            "suffix": null,
            "birthDate": null,
            "ssn": null,
            "fid": null,
            "gender": "",
            "licNum": null,
            "licStateCD": null,
            "maritalStatusCD": null,
            "relationshipToInsCD": "A",
            "businessName": null,
            "participantRole": "PRIMARY_INSURED"
        }
    ],
    "vehicles": [],
    "drivers": [
        {
            "driverId": 0,
            "firstName": "KHAGENDRA",
            "middleName": null,
            "lastName": "SIRIPURAPU",
            "licenseAtAge": 0,
            "licenseStatusCode": null,
            "defenseDriverCourseIndicator": null,
            "goodStudentIndicator": null,
            "driverTrainingIndicator": null,
            "awayAtSchoolIndicator": null,
            "incidents": null,
            "occupation": null,
            "insuredOnOther": null,
            "continuousCoverageIndicator": null,
            "priorLicenseNumber": null,
            "driverCourseDate": null,
            "driverCourseName": null,
            "firstLicenseNonUSA": null,
            "awayAtMilitaryIndicator": null,
            "sr22FilingIndicator": null,
            "otherPolicyCarrierName": null,
            "awayAtSchoolComment": null,
            "licenseOosPrior3YrsInd": "N",
            "licenseOosPrior3YearsStateCd": null,
            "advDriverTrainingDate": null,
            "defensiveDriverCourseDate": null,
            "otherPolicyTypeCode": null,
            "accidentPrvntCourseDate": null,
            "phoneNumber": null,
            "safetyPledgeInd": null,
            "accidents": null,
            "violations": null
        }
    ],
    "priorCarrier": {
        "priorBiLimits": null,
        "priorCarrName": null,
        "policyKey": 0,
        "continuousCoverageDesc": null,
        "lapsedReason": null,
        "numOfYearOfContinuousCoverage": null,
        "activeCurrentPoilcyInd": null
    },
    "discounts": null,
    "companionPolicy": null,
    "payment": null

},
    "allInsuredInd": "Y",
    "medicareMediaidInd": "Y",
    "driversGreaterthan65": true
}

POJO类:

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;
    }
... }

推荐答案

默认情况下,Jackson的数据绑定将尝试使用无参数构造函数构造一个对象,然后从JSON的相应位填充该对象的属性.您可以使用注释覆盖此行为

By default Jackson's data binding will try to construct an object using a no-argument constructor and then fill in the object's properties from the corresponding bits of the JSON. You can override this behaviour with annotations

@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 注释告诉Jackson调用哪个构造函数,并用

The JsonCreator annotation tells Jackson which constructor to call, and its parameters are annotated with JsonProperty to indicate which properties in the JSON correspond to which parameters in the constructor. Additional properties in the JSON that do not correspond to constructor arguments will be injected via setters or direct field access as normal.

这篇关于为什么Json不要求Junit测试使用任何参数构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆