json 2打字稿映射给出类型错误

时间:2018-09-28 13:59:03

标签: json typescript angular5

好吧,所以我试图通过Web Api 2将.Net对象列表映射到我的Angular前端。我收到了对象,但是根据情况的不同,对象及其属性可能是雇佣参考。 ,工作分配参考或工作分配组织单位参考。

这是一个对象列表外观的图像,其中一个AssignmentHolder可以是这三个类之一,而DependentEntities列表可以是这三个类之一。 enter image description here 这是它们在我的Angular应用中的外观:

这是包含它们的对象:

@JsonObject('AssignmentListItem')
export class AssignmentListItem {
@JsonProperty('AssignmentHolder')
AssignmentHolder: any = undefined;

@JsonProperty('DependentEntities')
DependentEntities: any = undefined;

@JsonProperty('AssignmentRoles', [AssignmentRole])
AssignmentRoles: AssignmentRole[] = undefined;

@JsonProperty('NumberOfDependentEntities', Number)
NumberOfDependentEntities: Number = undefined;

@JsonProperty('IsInherited', Boolean)
IsInherited: boolean = undefined;
}

这些是类。

@JsonObject('ReferenceBase')
export class ReferenceBase {

@JsonProperty('OrganizationRegistrationNumber', OrganizationRegistrationNumber)
OrganizationRegistrationNumber: OrganizationRegistrationNumber = undefined;

@JsonProperty('IsIncomplete', Boolean)
IsIncomplete: Boolean = undefined;

@JsonProperty('SortingName', String)
SortingName: string = undefined;
}

-------

@JsonObject('EmploymentReference')
export class EmploymentReference extends ReferenceBase {

@JsonProperty('NationalCivicRegistrationNumber', String)
NationalCivicRegistrationNumber: NationalCivicRegistrationNumber = undefined;

@JsonProperty('GivenName', String)
GivenName: string = undefined;

@JsonProperty('Surname', String)
Surname: string = undefined;

@JsonProperty('FullName', String)
FullName: string = undefined;

constructor() {
    super();
    this.FullName = (this.GivenName + ' ' + this.Surname);
    this.SortingName = this.FullName;
}
}

-----
@JsonObject('AssignmentReference')
export class AssignmentReference extends ReferenceBase {

@JsonProperty('AssignmentRoles', [AssignmentRole])
AssignmentRoles: AssignmentRole[] = undefined;

@JsonProperty('OrganizationName', String)
OrganizationName: string = undefined;

@JsonProperty('NationalCivicRegistrationNumber', NationalCivicRegistrationNumber)
NationalCivicRegistrationNumber: NationalCivicRegistrationNumber = undefined;

@JsonProperty('Surname', String)
Surname: string = undefined;

@JsonProperty('FullName', String)
FullName: string = undefined;

@JsonProperty('GivenName', String)
GivenName: string = undefined;
}

------

@JsonObject('AssignmentOrganizationalUnitReference')
export class AssignmentOrganizationalUnitReference extends ReferenceBase {

@JsonProperty('OrganizationName', String)
OrganizationName: string = undefined;

@JsonProperty('Name', String)
Name: string = undefined;

@JsonProperty('Active', Boolean)
Active: Boolean = undefined;

@JsonProperty('IncludeSubUnits', Boolean)
IncludeSubUnits: Boolean = undefined;

@JsonProperty('AssignmentRoles', [AssignmentRole])
AssignmentRoles: AssignmentRole[] = undefined;

@JsonProperty('UnitId', String)
UnitId: string = undefined;

@JsonProperty('Type', OrganizationalUnitReferenceType)
Type: OrganizationalUnitReferenceType = undefined;
}

所以这些也是我要映射的对象,具体取决于我返回的任务列表中的内容

这是我的自定义DTO,因此我可以使用自定义转换器:

@JsonObject('AssignmentsDto')
export class AssignmentsDto {

@JsonProperty('AssignmentList', ObjectConverter)
AssignmentList: AssignmentListItem[] = undefined;
}

这是我的JsonCustomConverter

@JsonConverter
export class ObjectConverter implements JsonCustomConvert<AssignmentListItem[]> {

// We receive the instance and just serialize it with the standard json2typescript method.
serialize(assignmentListItems: AssignmentListItem[]): any {
    const jsonConvert = new JsonConvert();
    return jsonConvert.serialize(assignmentListItems);
}

// We receive a json object (not string) and decide
// based on the given properties whether we want to
// create an instance of AssignmentReference or AssignmentOrgUnitReference.
deserialize(assignmentListItems: any): AssignmentListItem[] {

    const jsonConvert = new JsonConvert();

    let assignments = new Array<AssignmentListItem>();

    //Map the Holder entity.
    for (let assignment of assignmentListItems) {
        if (assignment.AssignmentHolder['__type'] === 'something.something.Web.Models.EmploymentReference' ||
            assignment.AssignmentHolder['__type'] === 'something.something.Web.Models.AssignmentEmploymentReference') {

            let tempAssignment: AssignmentListItem = jsonConvert.deserialize(assignment.AssignmentHolder, EmploymentReference);

            //For every assignment there is a list of Dependents. Here we map those.
            for (let dependent of assignment.DependentEntities) {
                if (dependent['__type'] === 'something.something.Web.Models.EmploymentReference' ||
                    dependent['__type'] === 'something.something.Web.Models.AssignmentEmploymentReference') {

                    let tempDependent: EmploymentReference = jsonConvert.deserialize(dependent, EmploymentReference);
                    tempAssignment.DependentEntities.push(tempDependent);

                } else if (dependent['__type'] === 'something.something.Web.Models.AssignmentOrganizationalUnitReference') {

                    let tempDependent: AssignmentOrganizationalUnitReference = jsonConvert.deserialize(dependent, AssignmentOrganizationalUnitReference);
                    tempAssignment.DependentEntities.push(tempDependent);
                }
            }

            assignments.push(tempAssignment);

        } else if (assignment.AssignmentHolder['__type'] === 'something.something.Web.Models.AssignmentOrganizationalUnitReference') {

            let tempAssignment: AssignmentListItem = jsonConvert.deserialize(assignment.AssignmentHolder, AssignmentOrganizationalUnitReference);

            //For every assignment there is a list of Dependents. Here we map those.
            for (let dependent of assignment.DependentEntities) {
                if (dependent['__type'] === 'something.something.Web.Models.EmploymentReference' ||
                    dependent['__type'] === 'something.something.Web.Models.AssignmentEmploymentReference') {

                    let tempDependent: EmploymentReference = jsonConvert.deserialize(dependent, EmploymentReference);
                    tempAssignment.DependentEntities.push(tempDependent);

                } else if (dependent['__type'] === 'something.something.Web.Models.AssignmentOrganizationalUnitReference') {

                    let tempDependent: AssignmentOrganizationalUnitReference = jsonConvert.deserialize(dependent, AssignmentOrganizationalUnitReference);
                    tempAssignment.DependentEntities.push(tempDependent);
                }
            }
            assignments.push(tempAssignment);
        }
    }
    console.log('return ', assignments);
    return assignments;
}
}

最后,这是我使用转换器的Assignment Api服务。

    // GET LIST OF ASSIGNMENTS
getAssignmentList(
    filterStr: string,
    orgNoParam: string,
    skip: number,
    take: number
): Observable<any> {

    // set headers
    let head = new HttpHeaders();
    head = head.append('Content-Type', 'application/json'); 
    // set binds to model reciever
    const data = {
        'orgNoParam': orgNoParam,
        'filterStr': filterStr,

    };
    let body = JSON.stringify(data);

    // set query parameters
    let url = this.assignmentListUrl + '?skip=' + skip + '&take=' + take;

    return this.http.post<any>(url, body, { headers: head })
        .map(this.convertData)
        .catch(this.handleError);
}

private convertData(res: Response) {

    let jsonConvert = new JsonConvert();
    jsonConvert.valueCheckingMode = ValueCheckingMode.ALLOW_NULL;

    let deSerializedAssignments: AssignmentListItem[] = jsonConvert.deserialize(res, AssignmentsDto).AssignmentList;

    return deSerializedAssignments;

我在控制台中遇到的错误是:

JsonConvert中的致命错误。由于类型错误,无法将JSON对象映射到JavaScript类“ AssignmentsDto”。类属性:AssignmentList预期类型:未定义的JSON属性:AssignmentList JSON类型:[对象,对象,对象,对象,对象]

1 个答案:

答案 0 :(得分:0)

我通过确保将json对象中的每个单个属性都映射到typescript类来解决此问题,并在AssignmentsDto中添加了第二个object属性以及转换器,如下所示:

@JsonProperty('AssignmentList',[AssignmentListItem],ObjectConverter) AssignmentList:AssignmentListItem [] =未定义;

希望这对某人有帮助!