C#dynamic解析C#Facebook sdk问题的搜索结果

时间:2012-11-29 09:26:44

标签: c# facebook-c#-sdk

尝试在Facebook上执行搜索页面

    if (sq.ObjectType.Equals("page"))
    {
        searchPath = "/search";

        req.q = sq.Query;
        req.type = sq.ObjectType;

    }

    dynamic results = FBClient_.Get(req);

我无法弄清楚如何解析结果。 我不能简单地循环它们。

我无法看到结构,因为它是动态对象 在某个地方,它有这种结构:

{
   "data": [
      {
         "name": "Platform-3",
         "category": "Health/medical/pharmacy",
         "id": "362034114769"
      },
      {
         "name": "Platform Expos",
         "category": "Product/service",
         "id": "521000451259682"
      },
      {
         "name": "eXo Platform",
         "category": "Software",
         "id": "152603664817327"
      },
      {
         "name": "Platform 28",
         "category": "Bar",
         "id": "104411956289378"
      },
}

但如何得到它我不确定。如何将其转换为可读格式?

2 个答案:

答案 0 :(得分:1)

以下是一些映射。

objects => IDictionary<string, object> or IDictionary<string, dynamic>
arrays => IList<object> or IList<dynamic>
number => long if whole number, double if have decimal values
string => string
boolean => bool

所以在你的情况下你可以这样做。

dynamic result = fb.Get("...")
foreach(var data in result.data) {
    var name = data.name;
    var category = data.category;
    var id = data.id
}

由于result.data是动态的,实际上是IList<object>,因此您可以使用foreach。你也可以尝试一下。

dynamic result = fb.Get("...")
IList<dynamic> data = result.data;
foreach(var d in data) {
    string name = d.name;
    string category = d.category;
    string id = d.id
}

或者你强烈输入。

public class SearchResults {
    public IList<SearchResult> data { get; set;}
}

public class SearchResult {
    public string id { get; set; }
    public string name { get; set; }
    public string category { get; set; }
}

var result = fb.Get<SearchResults>(...)

如果您想遵循C#命名标准,请使用DataContractDataMember

[DataContract]
public class SearchResults {
    [DataMember(Name = "data")]
    public IList<SearchResult> Data { get; set;}
}

[DataContract]
public class SearchResult {
    [DataMember(Name = "id")]
    public string Id { get; set; }

    [DataMember(Name = "Name")]
    public string Name { get; set; }

    [DataMember(Name = "Category")]
    public string Category { get; set; }
}

答案 1 :(得分:0)

您可能需要创建强类型类来表示prabir发布的JSON数据,或者您可以使用Json.NET等JSON库,这样您就可以更轻松地与数据进行交互。以下是其页面中的示例:

string json = @"{
  ""Name"": ""Apple"",
  ""Expiry"": new Date(1230422400000),
  ""Price"": 3.99,
  ""Sizes"": [
    ""Small"",
    ""Medium"",
    ""Large""
  ]
}";

JObject o = JObject.Parse(json);

string name = (string)o["Name"];
// Apple

JArray sizes = (JArray)o["Sizes"];

string smallest = (string)sizes[0];