What to do with a JSON Object Response?
I was working with Google Oauth 2 and finally was able to get the access token. Google simply returned the access token in a JSON object. The output was printed out on my browser. Since I've never touched JSON or any other API before, I have no idea how to capture that JSON object so I can store the access token.
Example Output(obscured the actual data)
{
"access_token":"1/6GKFqrOr6000000004k10qgr000000GiUiRNbLnc",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token": "1/Vx34LfPISDuX000000Kq_SJWIgf42FVs"
}
I tried the simple $token = $_POST['access_token']; which didn't work. json_decode also didn't work. I'm pretty sure I'm not doing it right here. Can someone tell me how you can interact with JSON object?
EDIT:
I guess my initial question is more rudimentary because I'm really new at API programming. What I want to know is how to encapsulate the browser response of a JSON object into a variable so my PHP script can dynamically decode the response. Currently, the browser just replied the content of the JSON object like I posted above but I don't know the object name or variable name like $object = {}. Is there any way to find out the object name or a way to put the respons开发者_如何转开发e into an object or array dynamically?
{
"access_token":"1/6GKFqrOr6000000004k10qgr000000GiUiRNbLnc",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token": "1/Vx34LfPISDuX000000Kq_SJWIgf42FVs"
}
Put this complete response in Json Object : Then JSONObject jObject = new JSONObject(response);
Now get your access token: String value= jObject.getString("access_token"); http://developer.android.com/reference/org/json/JSONObject.html
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
Did you try with json_decode($output,true). If you give the second parameter it will return an associative array.
I just ran this and it worked like a charm:
$f = <<<HER
{
"access_token":"1/6GKFqrOr6000000004k10qgr000000GiUiRNbLnc",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token": "1/Vx34LfPISDuX000000Kq_SJWIgf42FVs"
}
HER;
$c = json_decode($f);
echo $c->access_token;
Were you trying to access the property like it was an array? In this case $c['access_token']
would fail -- $c is not an array, it is an object. This is why I just used $c->access_token;
to output the result. If you'd like, you can pass TRUE as the second parameter to json_decode, but truth be told, I don't know if that is really necessary.
精彩评论