我正在开发一个Asp.Net mvc应用程序。 在我的应用程序中,我需要从远程服务器检索json对象。 我正在使用Web客户端。 但它给了我错误。 我的情况如下。
我有这个网址
http://graph.facebook.com/{fb_id}/picture?width=200&height=200&redirect=false当我从浏览器访问时,它会返回类似这样的内容
所以我试图以json的形式检索这些数据,然后将它们序列化回来。 所以我构建了两个类,如下所示来绑定数据。
public class FacebookAvatarResponse { [JsonProperty("data")] public FacebookAvatarData Data { get; set; } } public class FacebookAvatarData { [JsonProperty("height")] public int Height { get; set; } [JsonProperty("width")] public int Width { get; set; } [JsonProperty("is_silhouette")] public bool IsSilhouette { get; set; } [JsonProperty("url")] public string Url { get; set; } }在controll中,我构建了一个动作方法
[AllowAnonymous] public JsonResult Test(string avatarDataUrl) { using (WebClient webClient = new WebClient()) { string data = webClient.DownloadString(avatarDataUrl); return Json(JsonConvert.DeserializeObject<FacebookAvatarResponse>(data),JsonRequestBehavior.AllowGet); } }正如您所看到的,我将该数据作为json获取,然后作为操作结果返回。 但是当我请求那个传递正确的url作为参数的action方法时,它给了我这个错误。
我如何从远程服务器绑定到特定类中检索JSON数据?
I am developing an Asp.Net mvc application. In my application, I need to retrieve json object from remote server. I am using web client for it. But it is giving me error. My scenario is below.
I have this url
http://graph.facebook.com/{fb_id}/picture?width=200&height=200&redirect=falseWhen I access from browser, it return something like this
So I am trying to retrieve that data as json and then serialize them back. So I builds two classes like below to bind that data.
public class FacebookAvatarResponse { [JsonProperty("data")] public FacebookAvatarData Data { get; set; } } public class FacebookAvatarData { [JsonProperty("height")] public int Height { get; set; } [JsonProperty("width")] public int Width { get; set; } [JsonProperty("is_silhouette")] public bool IsSilhouette { get; set; } [JsonProperty("url")] public string Url { get; set; } }In controll, I built an action method
[AllowAnonymous] public JsonResult Test(string avatarDataUrl) { using (WebClient webClient = new WebClient()) { string data = webClient.DownloadString(avatarDataUrl); return Json(JsonConvert.DeserializeObject<FacebookAvatarResponse>(data),JsonRequestBehavior.AllowGet); } }As you can see I am getting that data as json and then return as action result. But when I request that action method passing correct url as parameter, it is giving me this error.
How can I retrieve JSON data from remote server binding to the specific classes?
最满意答案
可能你没有将JSON传递给DeserializeObject。
JsonConvert.DeserializeObject接受JSON值。
检查您的数据应采用json格式进行反序列化。
Json(JsonConvert.DeserializeObject<FacebookAvatarResponse>(data), JsonRequestBehavior.AllowGet);Possibly your are not passing JSON to DeserializeObject.
JsonConvert.DeserializeObject takes JSON value.
Check your data should be in json format to deserialize.
Json(JsonConvert.DeserializeObject<FacebookAvatarResponse>(data), JsonRequestBehavior.AllowGet);更多推荐
发布评论