从 JSON 解析 Typescript 中具有空值的映射

Parsing Map with null value in Typescript from JSON

我在 Typescript 中使用以下 class 来解析使用 TypedJson.parse()

作为 JSON 收到的员工数据
@JsonObject()
export class Employee { 

    @JsonMember()
    public name: string;

    @JsonMember()
    public columns: { [name: string]: any };
}

columns 是从 Spring 后端发送的 Map<String, Object>

在解析 TypedJson 时忽略所有值为 null 的键,因此不会创建 myKey: null 形式的键值对对象。我没有将所有 null 替换为 ''

的选项

如何将这些空值解析为具有 null 个值的对象?

因此,我看到了 TypedJson 的代码 - 在当前版本 0.1.7 中它是一个错误,但在存储库中这个错误已修复,但尚未发布。

因此您可以在下一个版本之前使用解决方法,只需添加 = null! 作为 属性 默认值:

    @JsonObject()
    export class Employee { 

        @JsonMember()
        public name: string = null!;

        @JsonMember()
        public columns: { [name: string]: any } = null!;
    }

正如@JonnyAsmar 所建议的那样,JSON.parse 适用于这种情况。

我之前在做

this._http.get(`${HTTP_URL}/${params.EmployeeId}/EmployeeData`, { params: params })
      .map(response => TypedJSON.parse(response.text(), Employee)
      })
      .catch(this.handleError);

作为我现在正在做的解决方法:

this._http.get(`${HTTP_URL}/${params.EmployeeId}/EmployeeData`, { params: params })
      .map(response => {
        let obj:JSON = JSON.parse(response.text());
        return obj;
      })
      .catch(this.handleError);