如何从JSON字符串中获取数据

时间:2016-08-03 03:24:12

标签: c# json facebook class facebook-graph-api

有点解释。我使用Facebook API与我的C#应用​​程序集成。自Facebook更新了API。我有问题要保持Facebook返回的JSON结果在我的代码中使用。以前是Facebook在JSON对象中返回的结果。我知道如何使用JSON对象。

现在问题是JSON以字符串形式返回。我该怎么做才能从JSON字符串中捕获数据?

这是Facebook提供的JSON

{"id":"t_mid.1468318160994:4fbaede7284fc37853","messages":{"data":[{"created_time":"2016-07-12T10:09:21+0000","id":"m_mid.1468318160994:4fbaede7284fc37853"}],"paging":{"previous":"https://graph.facebook.com/v2.6/t_mid.1468318160994:4fbaede7284fc37853/messages?access_token=[ACCESS-TOKEN]&limit=25&since=1468318161&__paging_token=[ACCESS-TOKEN]&__previous=1","next":"https://graph.facebook.com/v2.6/t_mid.1468318160994:4fbaede7284fc37853/messages?access_token=[ACCESS-TOKEN]&limit=25&until=1468318161&__paging_token=[ACCESS-TOKEN]"}}}
    base {System.Dynamic.DynamicObject}: {"id":"t_mid.1468318160994:4fbaede7284fc37853","messages":{"data":[{"created_time":"2016-07-12T10:09:21+0000","id":"m_mid.1468318160994:4fbaede7284fc37853"}],"paging":{"previous":"https://graph.facebook.com/v2.6/t_mid.1468318160994:4fbaede7284fc37853/messages?access_token=[ACCESS-TOKEN]&__previous=1","next":"https://graph.facebook.com/v2.6/t_mid.1468318160994:4fbaede7284fc37853/messages?access_token=[ACCESS-TOKEN]&limit=25&until=1468318161&__paging_token=[ACCESS-TOKEN]"}}}
    Count: 2
    IsReadOnly: false
    Keys: Count = 2
    Values: Count = 2

这是我从字符串中获取数据的代码

public class GetMesaggeIDUsingConversationID_API_V2_6
{
    public messages id { get; set; }
    public class messages
    {
        public Data[] data { get; set; }
        public class Data
        {
            public string id { get; set; }
        }
    }
}

List<GetMesaggeIDUsingConversationID_API_V2_6> msgApiforGetMsgID = JsonConvert.DeserializeObject<List<GetMesaggeIDUsingConversationID_API_V2_6>>("JSON STRING HERE");

但它变成了错误。

错误是:

"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.Generic.List<Orlig_Server_Services.Components.Refer.GetMesaggeIDUsingConversationID_API_V2_6>>(string)' has some invalid arguments\r\n   at CallSite.Target(Closure , CallSite , Type , Object )\r\n   at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)\r\n   at Orlig_Server_Services.Components.FacebookIntegration.getFanMessage() in D:\\Projects\\Orlig_FB_Service V3.2 API V2.6\\Components\\FacebookIntegration.cs:line 2874"

请给我一些建议。在此先感谢!

1 个答案:

答案 0 :(得分:0)

您的字符串采用JSON格式。您想要解析它们,因此您需要使用JSON.NET

string source = "JSON..."
dynamic data = JObject.Parse(source);

Console.WriteLine(data.id);
Console.WriteLine(data.messages);
// ...