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

发布于 2024-12-08 14:03:34 字数 1158 浏览 0 评论 0原文

我正在尝试使用 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]' (...)

I'm trying to parse some JSON using the Newtonsoft.Json library. The documentation seems a little sparse and I'm confused as to how to accomplish what I need. Here is the format for the JSON I need to parse through.

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

I'm trying to convert JSON data a nice object of some kind. Here is my class:

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>));

But i always get an error. Any ideas?

EDIT:
I get an Error:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

可爱咩 2024-12-15 14:03:34

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

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);

}

This is a bit ugly, but may suit your needs. It doesn't use a third party solution either. Apologies if it is a bit 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);

}
海螺姑娘 2024-12-15 14:03:34

示例:

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

Sample:

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);
    }
}

OUTPUT:

error:0
data:type any data(1674), size:45678
data:type any data(1256), size:12345
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文