Behseini Behseini - 3 years ago 115
C# Question

How To Read JSON From a Rest URL and Load to an Array

Can you please let me know if I have a rest service URL like

http://domain.ca/ArcGIS/rest/services/appData?f=json&pretty=true


which the JSON looks like

{"currentVersion" : 10.05,
"folders" : [],
"services" : [
{"name" : "appData/Drainage", "type" : "MapServer"},
{"name" : "appData/Parks", "type" : "MapServer"},
{"name" : "appData/Planning", "type" : "MapServer"},
{"name" : "appData/QNet", "type" : "MapServer"},
{"name" : "appData/Sanitary", "type" : "MapServer"},
{"name" : "appData/Street_Lights", "type" : "MapServer"},
{"name" : "appData/Survey", "type" : "MapServer"},
{"name" : "appData/Transportation", "type" : "MapServer"},
{"name" : "appData/Water", "type" : "MapServer"}
]
}


How can set a request to the service in C# and load all names after
appData/
to an array called
servicesList
?

Answer Source

The following unit test demonstrates

How can set a request to the service in C# and load all names after appData/ to an array called servicesList ?

[TestClass]
public class UnitTest3 {
    public async Task GetServicesList() {
        var url = "http://domain.ca/ArcGIS/rest/services/appData?f=json";
        var client = new HttpClient();
        var response = await client.GetAsync(url);
        var json = await response.Content.ReadAsStringAsync();
        var model = JsonConvert.DeserializeObject<ServiceResponse>(json);
        var servicesList = model.services.Select(s => s.name.Replace("appData/", "")).ToArray();
    }

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

    public class ServiceResponse {
        public double currentVersion { get; set; }
        public IList<object> folders { get; set; }
        public IList<Service> services { get; set; }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download