Home > Enterprise >  Deserializing Json With Unknown Key - ASP.Net Core 3.1
Deserializing Json With Unknown Key - ASP.Net Core 3.1

Time:09-16

I'd like to deserialize the following JSON with .Net 3.1

My difficulty is the "1234" key for this object is unknown when this object is serialized. How could I deserialize this? The values I want to keep are the nested "first_name" and "last_name" attributes

{
   "1234":{
      "id":1234,
      "first_name":"John",
      "last_name":"Doe"
   }
}

Any help is appreciated!

CodePudding user response:

In case you're using the Newtonsoft.Json.JsonConverter library, you could create a custom JsonConverter to handle dynamic properties and override the ReadJson and WriteJson methods.

public class MyConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // write your custom read json
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // write your custom write json
    }
}

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConverter.htm

CodePudding user response:

You could use a dictionary:

public class Child
{
    [JsonPropertyName("id")]
    public string ID { get; set; }
    [JsonPropertyName("first_name")]
    public string FirstName { get; set; }
    [JsonPropertyName("last_name")]
    public string LastName { get; set; }
}

public class Parent
{
    public Dictionary<string, Child> Children { get; set; }
}

You can then enumerate through Children using Foreach or Linq.

  • Related