Quantcast
Viewing latest article 1
Browse Latest Browse All 23

Answer by Adel Tabareh for How can I deserialize JSON to a simple Dictionary in ASP.NET?

Here is my solution with System.Text.Json. You get a json string for the nested objects which in own turn can be converted to needed type later on.

public static Dictionary<string,string> JsonToDictionary(this string json)        {            var objectValues = JsonSerializer.Deserialize<Dictionary<string, object>>(json);            var stringValues = objectValues.Select(o => new KeyValuePair<string, string>(o.Key, o.Value?.ToString()));            return stringValues.ToDictionary(pair => pair.Key, pair => pair.Value);        }

Here is the usage example to fetch values from a nested object:

 var result= json.JsonToDictionary()["outerField"]                .JsonToDictionary()["innerField"];

Note that this solution does not cover the json objects starting as an array like [12, 13]. These objects can be read as an array in the begining and then the extension method can be applied on each item, in case the items are complex objects with their own properties.


Viewing latest article 1
Browse Latest Browse All 23

Trending Articles