Aakash Goutam
Aakash Goutam

Reputation: 43

accessing dictionary from a Json string in c#

I have a JSON string as a response from server which contains key value pairs like dictionary. Some of the keys can have dictionary as their values as well. I have to access values based on certain keys from the inner dictionary. How can i access them and store in a string?

Something like this:-

string JsonData = "{\"status\":\"BAD_REQUEST\",\"code\":400,\"errorsCount\":1,\"errors\":[{\"desciption\":\"Field cannot be blank\"}]}";

string toBeAccessedValue = Field cannot be blank;

Any help would be appreciated.

Upvotes: 1

Views: 73

Answers (1)

er-sho
er-sho

Reputation: 9771

You can use [JsonExtensionData] to deserialize your json to class object.

public class RootObject
{
    [JsonExtensionData]
    public Dictionary<string, JToken> data { get; set; }
}

And you can use above class like

RootObject ro = JsonConvert.DeserializeObject<RootObject>(JsonData);

var errors = ro.data["errors"].ToObject<JObject[]>();

string description = errors.FirstOrDefault().Property("desciption").Value?.ToString();

Console.WriteLine("description: " + description);

Console.ReadLine();

Alternative:

You can use below class structure that can be helpful to you to deserialize your json and retrieve any value that you want.

public class Error
{
    public string desciption { get; set; }
}

public class RootObject
{
    public string status { get; set; }
    public int code { get; set; }
    public int errorsCount { get; set; }
    public List<Error> errors { get; set; }
}

And you can use above class structure to deserealize your json like

RootObject rootObject = JsonConvert.DeserializeObject<RootObject>(JsonData);

string description = rootObject.errors.FirstOrDefault()?.desciption;

Console.WriteLine("description: " + description);

Console.ReadLine();

Edit:

If you want to deserialize your json with JavaScriptSerializer then.

JavaScriptSerializer serializer = new JavaScriptSerializer();

RootObject rootObject = serializer.Deserialize<RootObject>(JsonData);

string description = rootObject.errors.FirstOrDefault()?.desciption;

Console.WriteLine("description: " + description);

Console.ReadLine();

Output:

enter image description here

Upvotes: 1

Related Questions