0

How can I deserialize Json into C# objects that have ID's for the node keys? For example:

{
  "people" : {
    "1": {
       "firstname": "jim",
       "lastname": "brown"
    },
    "2": {
       "firstname": "kathy",
       "lastname": "jones"  
    }
  }
}

Would serialize into this C# class

public class JsonRoot {
   public List<Person> People { get; set; }
}

public class Person {
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

Is this possible to do using either a custom generic converter or json attributes?

Ryan Langton
  • 6,294
  • 15
  • 53
  • 103
  • 1
    Replace `List` with `Dictionary`. – dbc Jun 22 '21 at 14:52
  • See: [Query or deserialize json with dynamic keys using System.Text.Json](https://stackoverflow.com/q/60089463/3744182), which looks to be a duplicate, agree? or do you require the JSON object to be deserialized as a list? – dbc Jun 22 '21 at 14:55
  • You might be able to use `Dictionary` in .NET 5, see https://devblogs.microsoft.com/dotnet/whats-next-for-system-text-json/#new-features: [Support non-string dictionary keys](https://github.com/dotnet/runtime/issues/30524). – dbc Jun 22 '21 at 14:59
  • Your Json string and classes don't match. `people` is an object/dictionary whose keys are numbers and whose values don't have an `Id` property. You'll have to deserialize this using *matching* classes and then map them to the classes you want – Panagiotis Kanavos Jun 22 '21 at 15:09
  • Dictionary works for what I need, thanks! – Ryan Langton Jun 22 '21 at 15:12

1 Answers1

0

For this List will not give solution as there is no array in your json data.

Dictionary can be use and that is also two level. First dictionary contains only one key = person and its value is also dictionary and its key are "1" and "2" and value is person object.

class Program
{
    static string jsonData = @"{
                          ""people"" : {
                            ""1"": {
                               ""firstname"": ""jim"",
                               ""lastname"": ""brown""
                            },
                            ""2"": {
                               ""firstname"": ""kathy"",
                               ""lastname"": ""jones""  
                            }
                          }
                        }
                        ";
    static void Main(string[] args)
    {
        var datatextjson = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, Person>>>(jsonData);
        Console.WriteLine("Hello World!");
    }

    public class Person
    {
        public string firstname { get; set; }
        public string lastname { get; set; }
    }
}
dotnetstep
  • 17,065
  • 5
  • 54
  • 72