c#如何将Json数据转换为对象

时间:2011-10-06 09:02:55

标签: c# json deserialization

我正在尝试使用Newtonsoft.Json库解析一些JSON。文档似乎有点稀疏,我对如何完成我需要的东西感到困惑。这是我需要解析的JSON的格式。

const string json = @"{   ""error"" : ""0"", 
""result"" :
{
   ""1256"" : {
      ""data"" : ""type any data"", 
      ""size"" : ""12345""
   },
   ""1674"" : {
      ""data"" : ""type any data"", 
      ""size"" : ""12345""
   },
   // ... max - 50 items
}
}";

我正在尝试将JSON数据转换为某种类型的好对象。这是我的班级:

public class ListLink
{
    public String data{ get; set; }
    public String size { get; set; }
}

public class SubResult
{
    public ListLink attributes { get; set; }
}

public class Foo
{
    public Foo() { results = new List<SubResult>(); }
    public String error { get; set; }
    public List<SubResult> results { get; set; }
}
.....
List<Foo> deserializedResponse =  
    (List<Foo>)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(List<Foo>));

但我总是收到错误。有什么想法吗?

编辑: 我收到一个错误:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[ConsoleApplication1.Foo]' (...)

2 个答案:

答案 0 :(得分:0)

<强>示例:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public struct Element {
    public string data{ get; set; }
    public int size { get; set; }
}

class Sample {
    static public void Main(){
        const string json =
        @"{ ""error"" : ""0"", 
            ""result"" :
            {
               ""1256"" : {
                  ""data"" : ""type any data(1256)"", 
                  ""size"" : ""12345""
               },
               ""1674"" : {
                  ""data"" : ""type any data(1674)"", 
                  ""size"" : ""45678""
               },
            }
        }";
        dynamic obj =  JsonConvert.DeserializeObject(json);
        int error = obj.error;
        Console.WriteLine("error:{0}", error);
        dynamic result = obj.result;
        Dictionary<string, Element> dic = new Dictionary<string, Element>();
        foreach(dynamic x in result){
            dynamic y = x.Value;
            dic[x.Name] = new Element { data = y.data, size = y.size};
        }
        //check
        Element el = dic["1674"];
        Console.WriteLine("data:{0}, size:{1}", el.data, el.size);
        el = dic["1256"];
        Console.WriteLine("data:{0}, size:{1}", el.data, el.size);
    }
}

<强>输出:

error:0
data:type any data(1674), size:45678
data:type any data(1256), size:12345

答案 1 :(得分:0)

这有点难看,但可能适合您的需求。它也不使用第三方解决方案。道歉,如果它有点kludgey !!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

const string json = @"{   ""error"" : ""0"", 
                            ""result"" :
                            {
                               ""1256"" : {
                                  ""data"" : ""type any data"", 
                                  ""size"" : ""123456""
                               },
                               ""1674"" : {
                                  ""data"" : ""type any data"", 
                                  ""size"" : ""654321""
                               },
                               ""1845"" : {
                                  ""data"" : ""type any data"", 
                                  ""size"" : ""432516""
                               },
                                ""1956"" : {
                                  ""data"" : ""type any data"", 
                                  ""size"" : ""666666""
                               }
                            }
                            }";

JavaScriptSerializer j = new JavaScriptSerializer();

var x = (Dictionary<string, object>)j.DeserializeObject(json);

Foo foo = new Foo();

foo.error = x["error"].ToString();

foreach (KeyValuePair<string, object> item in (Dictionary<string, object>)x["result"])
{

    SubResult result = new SubResult();

    ListLink listLink = new ListLink();

    var results = (Dictionary<string, object>)item.Value;

    foreach (KeyValuePair<string, object> sub in results)
    {

        listLink.data = results.First().Value.ToString();
        listLink.size = results.Last().Value.ToString();

    }

    SubResult subResult = new SubResult { attributes = listLink };

    foo.results.Add(subResult);

}