将字典转换为 c# 对象

时间:2021-03-08 18:53:49

标签: c# asp.net .net model-view-controller c#-4.0

我有一个嵌套的字典对象输出,如下所示

{
"name":"test",
"id":1,
"parent": {
      "name":"test1",
      "id":2,
      "parent":{
           "name":"test2",
           "id":3,
            "parent":{
                "name":"test3",
                "id":4,
                "parent":{
                    ....
                      }
                }
            }
      }
}

这是返回字典对象的代码:

class GetData
{
    public HttpWebResponse WebResponse { get; private set; }
    public Dictionary<string, object> Data { get; private set; }

    public GetData(HttpWebResponse webResponse, Dictionary<string, object> data)
    {
        WebResponse = webResponse;
        Data = data;
    }
}

我有一个包含上述响应的对象,如下所示:

var responseData = GetResponseData(req);

现在我想把上面的字典对象转换成c#对象。以下是我的c#对象

class SomeClass
{
    public int Id { get; }
    public string Name { get; }
    public SomeClass Parent { get; }
    
    public IEnumerable<SomeClass> GetAncestry()
    {
        if (Parent is not null)
        {
            yield return Parent;
            foreach (var ancestor in Parent.GetAncestry()) yield return ancestor;
        }
    }
}

我正在尝试以下方法将我的字典对象转换为“SomeClass”对象,但它对我不起作用。有人可以帮我解决这个问题吗?

List<SomeClass> smClass = new List<SomeClass>(responseData .Values);

1 个答案:

答案 0 :(得分:1)

尝试创建结构(或类),例如:

public class NamedObject
{
    int id {get; set;}
    string name {get; set;}
    NamedObject parent {get; set;}
}

然后您可以通过 Newtonsoft.Json.JsonConvert.DeserializeObject 反序列化您的 json(您需要 Newtonsoft.Json 库或 NuGet 包)

NamedObject namedObject = JsonConvert.DeserializeObject<NamedObject>(json);

工作示例(来自您之前的 question):

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

namespace ConsoleApp1
{
    internal class Program
    {

        private static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            string s = "{ \"name\":\"test\", \"id\":1, \"parent\": { \"name\":\"test1\", \"id\":2, \"parent\":{ \"name\":\"test2\", \"id\":3, \"parent\":{ \"name\":\"test3\", \"id\":4, \"parent\": null } } } }";
            TreeNode node = JsonConvert.DeserializeObject<TreeNode>(s);
        }
    }

    public class TreeNode
    {
        [JsonProperty("name")]
        public string Name { get; set; }
        [JsonProperty("id")]
        public int ID { get; set; }
        public NodeType Type { get; }
        public Dictionary<TreeNode, NodeType> Childern { get; }
        public TreeNode GetChildernByName(string name) => Childern.First(x => x.Key.Name == name).Key;
        [JsonProperty("parent")]
        public TreeNode Parent { get; private set; }
        public string FullName => IsRoot ? string.Empty : this.Parent.FullName + "/" + Name;
        public TreeNode(string name, NodeType type, TreeNode parent)
        {
            this.Name = name;
            this.Type = type;
            this.Parent = parent;
            this.Childern = new Dictionary<TreeNode, NodeType>();
        }
        public TreeNode()
        {

        }
        public TreeNode(string name) : this(name, NodeType.Folder, null) { }
        public TreeNode(string name, NodeType type) : this(name, type, null) { }
        public bool IsRoot => Parent == null;
        public void AddChild(params TreeNode[] nodes) => AddChild(true, nodes);
        public void AddChild(bool setParent, params TreeNode[] nodes)
        {
            foreach (TreeNode node in nodes)
            {
                Childern.Add(node, node.Type);
                if (setParent) node.Parent = this;
            }
        }
        public IEnumerable<TreeNode> GetFullPath()
        {
            List<TreeNode> parents = new List<TreeNode>();
            if (this.Parent != null)
            {
                parents.AddRange(Parent.GetFullPath());
            }
            parents.Add(this);
            return parents;
        }
        public override string ToString() => Name;
    }
    public enum NodeType
    {
        Folder,
        File
    }
}

您可以为公共字段使用与 json 中相同的名称,或者您可以在需要的地方设置 JsonProperty 属性。只记得,你必须有没有参数的构造函数,我建议使用可空类型(例如 int?)