简体   繁体   中英

How Do I De-Serialize JSON From the Facebook Graph API?

So i'm trying to de-serialize the JSON returned from the Graph API OAuth Token call.

The JSON looks like this:

"[{\\"access_token\\":\\"bunchofjsondatablahblah",\\"expires\\":9999}]"

I'm trying to de-serialize it (using the DataContractJsonSerializer class) into this object:

[DataContract]
internal class FacebookOAuthToken
{
     [DataMember]
     internal string access_token;

     [DataMember]
     internal string expires;
}

Here's how im (trying) to do it:

FacebookOAuthToken token;
using (Stream responseStream = (response.GetReponseStream()))
{
   DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(FacebookOAuthToken));
   token = (FacebookOAuthToken)json.ReadObject(responseStream);
}

This technique is based on this article from MSDN.

However, the properties of token are always null.

Whereas if i do responseStream.ReadToEnd() , it's all fine (returns the above JSON) - which means its not a problem with the actual HTTP request/response, i'm just not deserializing it properly.

What am i doing wrong?

Okay so it turns out i was using the wrong Graph API URL (so it seems).

This is the problem with the Facebook API Documentation, its all over the place and different threads (google, stack overflow) say different ways how to do things.

I changed to the URL https://graph.facebook.com/oauth/access_token ?{0} instead of https://graph.facebook.com/oauth/exchange_sessions ?{0} and it now returns a basic string (non-JSON).

So it doesnt need to be serialized at all.

Still, some people might have the same problem as me above, in that case im not sure how to solve.

I'm now using the method defined here .

If I interpret the JSON string correctly it represents a collection of FacebookOAuthToken items with one single instance in it and not just a single token.

Maybe that is why your deserialization did not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM