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

14

我对这个领域相对较新,如果我使用了一些错误的术语,请原谅。如有需要,可以随时要求澄清。

我有一些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
}

在正确(某种程度上)调用外部服务时,ItemResponse将被填充:

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

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

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

我该如何将这个转换成一个Item数组?

我知道如何将JSON解析为单个对象,但不知道如何处理数组。


1
你可以从让你的标题有意义开始 - 但你可能需要使用JSON.parse来解析JSON。 - Jaromanda X
可能是将带有逗号的字符串转换为数组的重复问题。 - Manish
3
@Manish 不是重复的。 - Derek Brown
1个回答

15

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

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

显然,这并没有对响应进行任何验证(这是不好的实践)。你最好对结果进行一些验证:

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){

}

或者,你也可以使用像ajv这样的JSON Schema验证工具。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接