How to get data from response body [duplicate]

2020-04-18 07:44发布

问题:

This question already has answers here:
Closed 2 years ago.

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