如何将json解析为angular 7对象?

时间:2019-05-02 19:40:52

标签: json angular rest

我正在尝试使用返回以下数据的Web API

{
"FileStatuses": {
    "FileStatus": [
        {
            "accessTime": 0,
            "blockSize": 0,
            "childrenNum": 13,
            "fileId": 16396,
            "group": "supergroup",
            "length": 0,
            "modificationTime": 1553247533630,
            "owner": "hduser",
            "pathSuffix": "demo-data",
            "permission": "755",
            "replication": 0,
            "storagePolicy": 0,
            "type": "DIRECTORY"
        },
        {
            "accessTime": 0,
            "blockSize": 0,
            "childrenNum": 7,
            "fileId": 16410,
            "group": "supergroup",
            "length": 0,
            "modificationTime": 1550659883380,
            "owner": "hduser",
            "pathSuffix": "instacart",
            "permission": "755",
            "replication": 0,
            "storagePolicy": 0,
            "type": "DIRECTORY"
        }
    ]
}
}

我创建了一个这样的服务,并创建了一个类来解析json响应:

  public getHadoopDirList(): Observable<FileStatus[]> {
return this.http.get<FileStatus[]>(this.webHdfsUrl, {}).pipe(map(data => data));
  }

   export class FileStatus {
accessTime: number;
blockSize: number;
childNum: number;
fileId: number;
group: string;
length: number;
modificationTime: number;
owner: string;
pathSuffix: string;
permission: string;
replication: number;
storagePolicy: number;
type: string;
}

我在组件上订阅了它,但是当我尝试在模板上对其进行迭代时,出现以下 ERROR错误:尝试与'[object Object]'进行比较时出错。仅允许数组和可迭代项

我认为问题在于如何映射它,但我不知道如何解决

2 个答案:

答案 0 :(得分:2)

  

使用http://json2ts.com/将JSON转换为接口

您的界面应如下所示

export interface FileStatus {
    accessTime: number;
    blockSize: number;
    childrenNum: number;
    fileId: number;
    group: string;
    length: number;
    modificationTime: any;
    owner: string;
    pathSuffix: string;
    permission: string;
    replication: number;
    storagePolicy: number;
    type: string;
}

export interface FileStatuses {
    FileStatus: FileStatus[];
}

export interface FileStatusesRootObject {
    FileStatuses: FileStatuses;
}

然后

return this.http.get<FileStatusesRootObject>(

答案 1 :(得分:1)

您需要确保数据类型匹配。它期望的结果类型为FileStatus[]。因此,在RxJS的map()上,您将需要通过选择FileStatus分别返回正确的数据,其中FileStatus包含类型为public getHadoopDirList(): Observable<FileStatus[]> { return this.http.get<FileStatus[]>(this.webHdfsUrl, {}) .pipe( map(data => data['FileStatuses']['FileStatus']) ); }

的对象数组
def act_results(request):
    '''
    display the acts suitable for a particular user
    '''
    template = loader.get_template('polls/act_results.html')
    try:
       Act = request.GET.get('Act')
       data = Act.objects.get(act__name=Act)
       return HttpResponse(template.render({'Act':Act},request))
    except Act.DoesNotExist:
       return HttpResponse(template.render({'error_msg':'Act does not exist for this Festival'}))