TypeScript - 如何将JSON数组解析为自定义对象数组

Cus*_*Bun 6 javascript typescript

我对这个领域比较陌生,如果我使用了一些错误的术语,我会道歉.随意要求澄清.

我有一些打字稿接口:

export interface Item {
    id: string
    type: string
    state: string
}

export interface ItemResponse {
    someData1: string
    someData2: string
    itemListResponse: Array<Item> // in reality just a JSON string containing serialized Items in an Array
}
Run Code Online (Sandbox Code Playgroud)

在(有些)正确调用外部服务时填充ItemResponse:

结果是ItemResponses的一个.现在,假设ItemResponse数组的大小为1,但itemListResponse数组中有多个Items.

itemListResponse实际上只是一个json字符串:

 "[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]"
Run Code Online (Sandbox Code Playgroud)

我如何将其转换为项目数组?

我认为我熟悉从JSON解析到单个对象,但不熟悉如何使用数组执行此操作.

Der*_*own 7

@Jaromanda X是正确的 - 您正在寻找JSON.parse.这样的东西就足够了:

responseArray =  "[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]"
<Item[]> JSON.parse(responseArray)
Run Code Online (Sandbox Code Playgroud)

显然,这不会对响应进行任何验证(这是不好的做法).理想情况下,您应该对结果进行更强烈的验证:

responseArray =  "[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]"

var result;
try {
   itemListResponse = <Item[]>JSON.parse(responseArray);

   if(!itemListResponse.has("id") ||
      !itemListResponse.has("type") ||
      !itemListResponse.has("state")){

      throw "Invalid Item";
   }
} catch (e){

}
Run Code Online (Sandbox Code Playgroud)

或者,也可以使用像ajv这样的JSON Schema验证器.