使用Newtonsoft JSON反序列化包含数组/列表的对象,使用字典。

huangapple go评论45阅读模式
英文:

using newtonsoft json deserialize object that contains array/list using dictionary

问题

我想将 JSON 转换为对象。下面的代码有效。

internal class Program
{
    static void Main(string[] args)
    {
        string json = @"{
                  'name': 'Ayrton Senna',
                  'friends': [
                    {
                      'name': 'John',
                      'age': 34
                    },
                    {
                      'name': 'Jack',
                      'age': 32
                    }
                  ]
                }";

        var person = JsonConvert.DeserializeObject<Person>(json);
    }

    public class Person
    {
        public string Name { get; set; }
        public List<Friend> Friends { get; set; }

        public class Friend
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }
}

然而,在 Person 类中,我希望属性 List<Friend> 变成字典。键将是字符串,应该从 JSON 中获取而不是硬编码。值将是对象列表。

示例:

public class Person
{
    public string Name { get; set; }
    public Dictionary<string, List<Friend>> Friends { get; set; }

    public class Friend
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

我之所以这样做是因为当我有不同的 JSON 时,例如:

{
  "id": 1,
  "name": "Ayrton Senna",
  "mates": [
    {
      "name": "John",
      "age": 12
    },
    {
      "name": "Jack",
      "age": 32
    }
  ]
}

另一个示例的 JSON:

{
  "id": 1,
  "name": "Ayrton Senna",
  "companions": [
    {
      "name": "John",
      "age": 12
    },
    {
      "name": "Jack",
      "age": 32
    }
  ]
}

我需要捕获/存储列表的名称,如 "friends"、"mates"、"companions",因为我以后需要显示它们。我将有 20 个类似的 JSON 文件,唯一不同的是这个属性的名称。所以我需要从 JSON 中读取它并以某种方式存储它。

我想要一个更 "通用" 的类。这是否可行?如果您有其他建议,请告诉我。将不胜感激。

英文:

I want to convert JSON to object. The code below works fine.

internal class Program
{
    static void Main(string[] args)
    {
        string json = @&quot;{
                  &#39;name&#39;: &#39;Ayrton Senna&#39;,
                  &#39;friends&#39;: [
                    {
                      &#39;name&#39;: &#39;John&#39;,
                      &#39;age&#39;: 34
                    },
                    {
                      &#39;name&#39;: &#39;Jack&#39;,
                      &#39;age&#39;: 32
                    }
                  ]
                }&quot;;

        var person = JsonConvert.DeserializeObject&lt;Person&gt;(json);
    }

    public class Person
    {
        public string Name { get; set; }
        public List&lt;Friend&gt; Friends { get; set; }

        public class Friend
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }
}

However in the Person Class I want the property List<Friend> to be dictionary.
The key will be string that should be "friends" (somehow taken from the Json and not hardcoded).
The value will be list of objects.

Example:

    public class Person
    {
        public string Name { get; set; }
        public Dictionary&lt;string, List&lt;Friend&gt;&gt; Friends { get; set; }

        public class Friend
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }

The reason I want this is so when i will have different JSON for example:

{
  &quot;id&quot;: 1,
  &quot;name&quot;: &quot;Ayrton Senna&quot;,
  &quot;mates&quot;: [
    {
      &quot;name&quot;: &quot;John&quot;,
      &quot;age&quot;: 12
    },
    {
      &quot;name&quot;: &quot;Jack&quot;,
      &quot;age&quot;: 32
    }
  ]
}

Another example Json:

{
  &quot;id&quot;: 1,
  &quot;name&quot;: &quot;Ayrton Senna&quot;,
  &quot;companions&quot;: [
    {
      &quot;name&quot;: &quot;John&quot;,
      &quot;age&quot;: 12
    },
    {
      &quot;name&quot;: &quot;Jack&quot;,
      &quot;age&quot;: 32
    }
  ]
}

I need to capture/store the name of the list like: "friends", "mates", "companions" because i will need to display them later. I will have 20 Json files like this and only this property name will be different. So i need to read ir from the json and store it somehow.

I want a class that will be more "generic".

Is this even doable? If you have some other suggestions please do tell. Any help will be much appreciated!

答案1

得分: 1

如果唯一的区别是数组的名称,您可以继续使用您已经有的类,并使用以下代码:

var jObj = JObject.Parse(json);
var friends =  jObj.Properties()
                  .Where(p => p.Value.Type == JTokenType.Array)
                  .SingleOrDefault();

Person person = jObj.ToObject<Person>();
person.FriendsKind = friends.Name;
person.Friends = friends.Value.Select(p => p.ToObject<Friend>()).ToList();

公共类 Person 如下:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string FriendsKind { get; set; }
    public List<Friend> Friends { get; set; }
}
英文:

if the only difference is the array name, you can leave the class you have already and use this code

	var jObj = JObject.Parse(json);
    var friends =  jObj.Properties()
                      .Where(p =&gt; p.Value.Type == JTokenType.Array)
                      .SingleOrDefault();
					
	Person person = jObj.ToObject&lt;Person&gt;();
    person.FriendsKind= friends.Name;
	person.Friends = friends.Value.Select(p =&gt; p.ToObject&lt;Friend&gt;()).ToList();

public class Person
{
	public int Id { get; set; }
	public string Name { get; set; }
	public string FriendsKind {get; set;}
	public List&lt;Friend&gt; Friends { get; set; }
}

答案2

得分: 1

以下是您要翻译的代码部分:

var jObj = JObject.Parse(json);
var friends = jObj.Properties().ToArray()[1];

var person = new Person
{
    Name = jObj.GetValue("name").Value<string>(),
    Friends = new Dictionary<string, List<Person.Friend>>
    {
        {
            friends.Name,
            friends.Value.Select(p => p.ToObject<Person.Friend>()).ToList()
        }
    }
};

public class Person
{
    public string Name { get; set; }
    public Dictionary<string, List<Friend>> Friends { get; set; }

    public class Friend
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}
英文:
    var jObj = JObject.Parse(json);
    var friends = jObj.Properties().ToArray()[1];
    
    var person = new Person
    {
        Name = jObj.GetValue(&quot;name&quot;).Value&lt;string&gt;(),
        Friends = new Dictionary&lt;string, List&lt;Person.Friend&gt;&gt;
        {
            {
                friends.Name,
                friends.Value.Select(p =&gt; p.ToObject&lt;Person.Friend&gt;()).ToList()
            }
        }
    };

    public class Person
    {
        public string Name { get; set; }
        public Dictionary&lt;string, List&lt;Friend&gt;&gt; Friends { get; set; }

        public class Friend
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }
    }

huangapple
  • 本文由 发表于 2023年2月14日 04:22:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440809.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定