代码之家  ›  专栏  ›  技术社区  ›  SirSpectacular

如何从响应体获取数据[重复]

  •  1
  • SirSpectacular  · 技术社区  · 9 年前

    我现在正在使用Java中的Youtube API,并设法将一些数据存储为 CommentThreadListResponse

    这里是其节点的示例,但列表包含大约100个节点。

    {
       "snippet" : {
         "topLevelComment" : {
           "snippet" : {
             "textDisplay" : "SOME COMMENT"
           }
         }
       }
     },
    

    所以只有 textDisplay

    2 回复  |  直到 9 年前
        1
  •  0
  •   Nisal Edu    9 年前

    让我们把你们的回答和分析,为了让它更容易理解,我将放置一些索引值,并考虑回应 议论

    //index0    {
            "id": "11",
            "snippet": {
                "topLevelComment": {
                    "snippet": {
                        "textDisplay": "SOME COMMENT 2 "
                    }
                }
            }
        },
    
     //index0   {
            "id": "22",
            "snippet": {
                "topLevelComment": {
                    "snippet": {
                        "textDisplay": "SOME COMMENT 2"
                    }
                }
            }
        },
    

    您将获得上述格式的响应,因此要获得每个代码段的详细信息,请浏览索引

    comment[0] 将提取响应的第一个元素。

    comment[0].id

    comment[0].snippet

    comment[0].snippet.topLevelComment 将提取响应的第一个片段的topLevelComment。

    comments[0].snippet.topLevelComment.snippet.textDisplay
    

    要遍历所有索引,您可以按如下方式对每个索引使用

    for (x in comments) {
    
      comments[x].snippet.topLevelComment.snippet.textDisplay
    
    }
    
        2
  •  0
  •   Daniel B    9 年前

    完全从yr问题中获得的数据结构并不清楚,但:

    var comments = [
    {
      "id": "1111",
       "snippet" : {
         "topLevelComment" : {
           "snippet" : {
             "textDisplay" : "SOME COMMENT 2 "
           }
         }
       }
     },
    {
      "id": "222",
     "snippet" : {
         "topLevelComment" : {
           "snippet" : {
             "textDisplay" : "SOME COMMENT 2"
           }
         }
       }
     },
    ]'
    

    你需要一个系列化库,签出 How to deserialize json string into object 然后

    for(var i = 0; i < comments.length; ++i)
      comments[i].snippet.topLevelComment.snippet.textDisplay