简体   繁体   中英

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.

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM