Search code examples
c#jsondeserialization

JSON Deserialize with change name field


I need to deserialize this json: { "name": { "field": "kop", "field2": false } }

But "Name" is already different, how I can do it? For example: one time it can be

{ "JOHN": { "field": "kop", "field2": false } }

, but another time it will be another name:

{ "BILL": { "field": "kop", "field2": false } } etc.


Solution

  • You need to use a dictionary:

    Dictionary<string, MyData>
    

    Like this:

        public class MyData
        {
            [JsonProperty("field")]
            public string Field { get; set; }
    
            [JsonProperty("field2")]
            public bool Field2 { get; set; }
        }
    

    Then deserialize like this:

    var result = JsonConvert.DeserializeObject<Dictionary<string, MyData>>(jsonStringGoesHere);
    

    So now the name will become the Key of the dictionary.

    You need to use Newtonsoft Json.

    You can get the data out like this:

    var myData = result["JOHN"];
    

    Or you can get the data like this:

    var myData = result.Values.ToList()[0];
    

    or you can get the KeyValuePair like this:

    var keyValPair = result.FirstOrDefault();
    

    Which then you can use the Key and Value properties to get both key and value. You will need to add using System.Linq to call FirstOrDefault()