ZZZ ZZZ - 2 months ago 6
JSON Question

Need to extract attribute and value(s) from json string

I have a Json string that I deserialized and turned into a dictionary that has 2 keys. I am interested in the key (services) which it's value contains h a string of services each with its own properties all in one line seperated by commas and parenthesis. I want to be able to loop over those services and get each one with it's properties. I thought regular expression would do it, but I cant find a matching pattern
`

responseDictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(response);
var services = responseDictionary["services"]


The value I get back has this pattern

"[\r\n {\r\n \"name\": \"extract\",\r\n \"type\": \"FeatureServer\"\r\n },\r\n {\r\n \"name\": \"extract\",\r\n \"type\": \"MapServer\"\r\n }\r\n]"


there are 2 services,

extract---of type featureserver.

extract---of type mapserver

What can I do to get those 2 services with thier type ?

BWA BWA
Answer

Your JSON after formating looks:

[{
    "name": "extract",
    "type": "FeatureServer"
},
{
    "name": "extract",
    "type": "MapServer"
}]

And can be mapped to class:

public class Service
{
    public string name { get; set; }
    public string type { get; set; }
}

So yo can deserialize it like this:

List<Service> services = JsonConvert.DeserializeObject<List<Service>>(response);

And loop for each service:

foreach(Service s in services)
{
    string name = s.name;
    string type = s.type;
}
Comments