简体   繁体   English

如何从Facebook Graph API反序列化JSON?

[英]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. 因此,我正在尝试反序列化从Graph API OAuth令牌调用返回的JSON。

The JSON looks like this: JSON如下所示:

"[{\\"access_token\\":\\"bunchofjsondatablahblah",\\"expires\\":9999}]" “ [{\\” access_token \\“:\\” bunchofjsondatablahblah“,\\”到期\\“:9999}]”

I'm trying to de-serialize it (using the DataContractJsonSerializer class) into this object: 我试图将它反序列化(使用DataContractJsonSerializer类)到该对象中:

[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. 此技术基于MSDN上的这篇文章。

However, the properties of token are always null. 但是, token的属性始终为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. 而如果我执行responseStream.ReadToEnd() ,一切都很好(返回上面的JSON)-这意味着它与实际的HTTP请求/响应无关,我只是没有正确地反序列化。

What am i doing wrong? 我究竟做错了什么?

Okay so it turns out i was using the wrong Graph API URL (so it seems). 好的,事实证明我使用的是错误的Graph API URL(看来)。

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. 这是Facebook API文档的问题,它遍地都是,不同的线程(谷歌,堆栈溢出)说出不同的操作方式。

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). 我将网址改为https://graph.facebook.com/oauth/access_token?{0 },而不是https://graph.facebook.com/oauth/exchange_sessions?{0 },它现在返回一个基本字符串(非-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. 如果我正确解释了JSON字符串,则它表示一个FacebookOAuthToken项目的集合,其中包含一个单一实例,而不仅仅是一个令牌。

Maybe that is why your deserialization did not work. 也许这就是为什么您的反序列化无效的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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