【问题标题】:Map JSON object into TypeScript Object将 JSON 对象映射到 TypeScript 对象
【发布时间】:2014-11-07 11:10:33
【问题描述】:

我正在使用 AJAX JQuery 从服务器返回一个对象数组,一个示例

[{"Name":"Name1","ResultSet":[{"Id": 1,"Name":"Name1"}, {"Id": 2,"Name":"Name2"}]},{"Name": "Name11", "ResultSet": [{"Id": 11, "Name": "Name11"}, {"Id": 22, "Name": "Name22"}]}]

另外,我有以下要映射的 TypeScript 对象

interface IResult {
   name: string;
   resultSet: any;
}

export class Result implements IResult {
    constructor(public name: string, public resultSet: any) { }
}

我处理结果的方式,

dataService.execute(function (results) {
    $(results).each(function (index, element) {
        console.log(element.Name);
            $.each(element.ResultSet, function (key, value) {
                $.each(value, function (key, value) {
                    console.log(key + ' - ' + value);
                });
            });
        });
    });

在 VS 2013 中,编译器抱怨:

The property 'Name' does not exist on value of type 'Element'.

有没有办法将返回的对象集合映射到 TS Result 对象数组?

谢谢

更新 我最终循环如下:

var result = <Array<IResult>>results;

$.each(result, function (index, item) {
      // item is Result instance
      // item.name
      console.log(item.name);

      // item.resulSet
      $.each(item.resultSet, function (key, val) {
            // val is single Object (one result)
            $.each(val, function (k, v) {
                  // k,v => key/value for each property on result
                    console.log(k + ' - ' + v);
            });
      });

});

【问题讨论】:

    标签: javascript jquery json typescript


    【解决方案1】:

    在 IResult 的接口定义中,属性是小写的,但您尝试使用大写来访问它们。由于您的 JSON 具有大写更改 IResult 为:

    interface IResult {
       Name: string;
       ResultSet: any;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-07
      • 2019-05-27
      • 1970-01-01
      • 2012-04-23
      • 2012-02-06
      • 2017-12-24
      • 1970-01-01
      • 2013-04-17
      • 1970-01-01
      相关资源
      最近更新 更多