0

我试图反序列化我从 facebook 检索到的 JSON 数据,但 c# 不允许它,因为当我尝试在公共类中声明它时,“F.18-24”是一个无效变量。我设法反序列化“公制”字段,但对于“F.18-24”字段,我不知道该怎么做。任何帮助,将不胜感激。为了让 c# 读取 F.18-24,它与Ext.data.Record有关吗?

我从 facebook 检索到的 JSON 数据:

{"data":[
{
    "metric":"page_fans_gender_age", 
    "value":
        {"F.18-24":19,
        "M.18-24":14,
        "M.25-34":4,
        "F.13-17":1,
        "M.13-17":1
}}]}

我的反序列化代码:

//geting isights data age & gender
    private void kryptonButton1_Click_2(object sender, EventArgs e)
    {
        try
        {

          var client = new FacebookClient(myToken.Default.token);
          var query = string.Format("SELECT metric, value FROM insights WHERE object_id=132414626916208 AND metric='page_fans_gender_age' AND period = period('lifetime') AND end_time = end_time_date('2013-01-18')");

            dynamic parameters = new ExpandoObject();
            parameters.q = query;
            dynamic results = client.Get("/fql", parameters);

            JavaScriptSerializer sr = new JavaScriptSerializer();
            String jsondata = String.Empty;
            jsondata = results.ToString();

            genderAgeDataII converted = sr.Deserialize<genderAgeDataII>(jsondata);
            Console.WriteLine(converted);
        }

        catch (Exception ex) {
            MessageBox.Show(ex.Message);
        }

    }


}

//class for JSON Deserialize
public class genderAgeDataII
{
    public genderAgeData[] data { get; set; }
}

public class genderAgeData
{
    public string metric { get; set; }
    public genderAge value { get; set; }
}

public class genderAge
{
    //public string numbers { get; set; }
    /*string f1824 = "F.18-24";
    string m1824 = "M.18-24";
    string m2534 = "M.25-34";
    string f1317 = "F.13-17";
    string m1317 = "M.13-17"; */

    public int f1824 { get; set; }
    public int m1824 { get; set; }
    public int m2534 { get; set; }
    public int f1317 { get; set; }
    public int m1317 { get; set; }
}
4

1 回答 1

0

FB C# SDK 支持泛型。您可以将其用作

var data = fb.Get<genderAgeDataII>("fql", parameters);

https://github.com/facebook-csharp-sdk/facebook-csharp-sdk/pull/203

然后使用数据契约和数据成员

[DataContract]
public class genderAge
{
    //public string numbers { get; set; }
    /*string f1824 = "F.18-24";
    string m1824 = "M.18-24";
    string m2534 = "M.25-34";
    string f1317 = "F.13-17";
    string m1317 = "M.13-17"; */

    [DataMember(Name="F.18-24")]
    public int f1824 { get; set; }
    .....
}
于 2013-01-25T04:33:30.917 回答