Reputation: 23
I have a function where I can get all JSON data from but I do not understand how to pick out specific data.
I am using dynamic variable to loop thought all JSON information.
How can I for example pick out all "names:" from the given JSON URL and display it in the console.
Fetching data with url:
public string FetchData(string url)
{
string String_jsonData;
using (WebClient client = new WebClient())
{
Uri SourceUri = new Uri(url);
String_jsonData = client.DownloadString(SourceUri);
}
return String_jsonData;
}
Main and run methode,
static void Main(string[] args)
{
Program p = new Program();
p.run();
Console.ReadKey();
}
public void run()
{
string url = "JSON URL;
dynamic pers = JsonConvert.DeserializeObject(FetchData(url));
// fetching all data. Here I want to select specific data and save it.
foreach (var item in pers)
{
Console.WriteLine(item);
}
}
Model Class:
class Person
{
public string name { get; set; }
public string ci_list { get; set; }
}
Here is an example of the data I want to fetch
{
"items": [
{
"ci_type": "xxx",
"exists_in_equipman": false,
"exists_in_hydra": false,
"exists_in_taxen": true,
"hns_name": false,
"id": xxx,
"latest_sync_info": {
"HYDRA": "xxx",
"TAXEN": "xxx"
},
"modified_url": "xxx",
"name": "xxx",
"params": {
"Band (4G)": {
"id": xxx,
"source": "script",
"source_name": "xxx",
"value": {}
},
"Hardware Specification": {
"id": xxx,
"source": "script",
"source_name": "taxen_import",
"value": {
"0": {
"3GPP release": {
"value": ""
},
"Accessories": {
"value": ""
},
"Category": {
"value": ""
},
"Hw rev": {
"value": "xxx"
},
"Locked": {
"value": ""
},
"Model family name": {
"value": "xxxx"
},
"Physical state": {
"value": "xxxx"
},
"Serial No": {
"value": "xxxx"
},
"Software": {
"value": ""
},
"Software version": {
"value": ""
}
}
}
},
Upvotes: 0
Views: 200
Reputation: 2689
First get data from url
var json = string.Empty;
string url = "http://";
using (var httpClient = new HttpClient())
{
json = httpClient.GetStringAsync(url).Result;
}
Then Deserialize object (assume is lest of objects)
List<dynamic> list = JsonConvert.DeserializeObject<List<dynamic>>(json);
foreach (var ar in list)
{
Console.WriteLine(ar["name"]); //assume object look like {"name":"saa", "age":"23"} and want to access name
}
Example in how to extract ci_type
value based on json object in your question
string json = "{\r\n\"items\": [\r\n{\r\n\"ci_type\": \"xxx\",\r\n\"exists_in_equipman\": false,\r\n\"exists_in_hydra\": false\r\n}\r\n]\r\n}";
var result = JsonConvert.DeserializeObject<dynamic>(json);
var data = result["items"];
foreach (var cityType in data)
{
Console.WriteLine(cityType["ci_type"]);
}
result : xxx
Upvotes: 1
Reputation: 62074
Your issue is that pers
is not directly an array, it's an object.
You need to loop over the "items" property which is held within it. This array is what contains the objects which have the "name" properties.
Change your loop code to
foreach (var item in pers.items)
Upvotes: 0