将json数据转换为datatable

时间:2014-09-18 10:43:30

标签: c# json datatable json.net

我尝试使用json.net将json数据转换为datatable,但我无法解决,是json的新手

我试过

代码:

 string json = JsonConvert.SerializeObject(friend);
 friends_info finfo   = JsonConvert.DeserializeObject<friends_info>(json); 

public class friends_info
{
    public friends_info()
    {

    } 

    public string name_; // Backing field
    public string name
    {
        get { return name_; }  // Getter
        set { name_ = value; } // Setter
    }
    public string id_; // Backing field
    public string id
    {
        get { return id_; }  // Getter
        set { id_ = value; } // Setter
    }
    }

 where string json="{"data":[{"name":"Angelina Jovy","id":"100000599264453"},{"name":"Luvbhie Rose May Aviles","id":"100001102845189"},{"name":"Nainy Ahuja","id":"100001103300515"},{"name":"Sabrina Reis","id":"100008357430263"}],"paging":{"next":"https://graph.facebook.com/v1.0/1539545690/friends?access_token=CAAGjOBYUDq0BAAFnIgfyfvMftE1ImSEfZCK7R7NdFYw5lnKuddHwqqlm20DTuZCjEeUh2hzMD0KAJpY1ozq3aPuh9nQUHBrXtG0Qu2sd6RwotUQtYj9jtGcMlJEzZCCBLLH8CZBSNQIZAzC2ASOxkYf3JCfwGZA7XSzF5y2iPVDWRCfrl8C4rZAZBzkJiaJwytVvSintYLRfySaunO81fAei&limit=5000&offset=5000&__after_id=enc_AewuVVCxM4Iz1IuazCHob3SZku3BDZ6NeU054UtCU_gc0QDAm2g2VNM__lcbuJNDtm9RmHLU-QCQifFun9H__Zqs"}}"

2 个答案:

答案 0 :(得分:2)

您要反序列化的类必须与JSON字符串匹配。

public class MyData
{
    public friends_info[] data { get; set; }
    public object paging { get; set; } // you can probably omit this
}

通过反序列化,给定的JSON字符串应该可以工作。

MyData myData = JsonConvert.DeserializeObject<MyData>(json);
friends_info finfo = myData.data;

除此之外,我非常建议您再次查看C#基础知识。即使你发布的那些小代码也违反了典型的编码惯例。

答案 1 :(得分:0)

我不确定,但我认为你的字符串格式不正确,应该是这样的。

&#34; {&#39;数据&#39;:[{&#39;名称&#39;:&#39; Angelina Jovy&#39;,&#39; id&#39;:&#39; ;&nbsp;&nbsp;&nbsp;&nbsp; #39;姓名&#39;:&#39; Nainy Ahuja&#39; id&#39;:&#39; 100001103300515&#39;},{&#39; name&#39;:&#39; ; Sabrina Reis&#39; id&#39;:&#39; 100008357430263&#39;}],&#39;寻呼&#39;:{&#39; next&#39;:&#39; https://graph.facebook.com/v1.0/1539545690/friends?access_token=CAAGjOBYUDq0BAAFnIgfyfvMftE1ImSEfZCK7R7NdFYw5lnKuddHwqqlm20DTuZCjEeUh2hzMD0KAJpY1ozq3aPuh9nQUHBrXtG0Qu2sd6RwotUQtYj9jtGcMlJEzZCCBLLH8CZBSNQIZAzC2ASOxkYf3JCfwGZA7XSzF5y2iPVDWRCfrl8C4rZAZBzkJiaJwytVvSintYLRfySaunO81fAei&limit=5000&offset=5000&__after_id=enc_AewuVVCxM4Iz1IuazCHob3SZku3BDZ6NeU054UtCU_gc0QDAm2g2VNM__lcbuJNDtm9RmHLU-QCQifFun9H__Zqs&#39;}}&#34 ;;

如果您的json字符串格式正确,那么@bstenzel建议应该可以正常工作。 感谢名单