How to get data from response body [duplicate]

独自空忆成欢 提交于 2019-12-02 10:59:28

问题


Im working right now with Youtube API in Java, and managed to get some data stored as CommentThreadListResponse

Here is an example of its node, but list contains about 100 of them.

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

So there is just textDisplay that remains, as something I'd like to extract into String. So my question goes "How can I do it?"


回答1:


Let take your response and analyse it, for make it more understandable I will place some index values, and consider response comment

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

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

You will get your response in above format, so to get details of each snippet navigate through indexes

comment[0] will extract the first element of the response.

comment[0].id will extract the first element id of the response.

comment[0].snippet will extract the first snippet of the response.

comment[0].snippet.topLevelComment will extract the first snippet's topLevelComment of the response.

So on like this we can read response and get the data we need in your case you need to get textDisplay so you can use following code,

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

To go through all indexes you can use for-each as following

for (x in comments) {

  comments[x].snippet.topLevelComment.snippet.textDisplay

}



回答2:


It's not clear the structure of data y r getting completely from yr question but:

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

you need a serilization lib, checkout How to deserialize json string into object then

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


来源:https://stackoverflow.com/questions/46793026/how-to-get-data-from-response-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!