我可以将REST JSON加载到数组中。但我需要将数据加载为词典以访问name
和type
,以便在treeView1
json看起来像
{"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"}
]
}
使用此代码,我只能在treevView上显示name
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("app/", "")).ToArray();
foreach (string value in servicesList)
{
treeView1.Nodes.Add(value);
}
喜欢:
但我需要像
这样的东西我已经像这样添加了字典
Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
bot不确定如何从那里检索数据并应用于treeView1
?
答案 0 :(得分:1)
如果您尝试从您提供的JSON中检索此类结果,则可以尝试使用此类
不确定ServiceResponse
是什么,所以我创建了它,仅用于演示
string json = @"{'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'}
]
}";
var model = JsonConvert.DeserializeObject<ServiceResponse>(json);
var services = model.Services.Select(t => new Service
{
Name = t.Name.Replace("appData/", ""),
Type = t.Type
}).OrderBy(t => t.Name).ToList();
foreach (var service in services)
{
string value = $"{service.Name} - ({service.Type})";
//treeView1.Nodes.Add(value);
Console.WriteLine(value);
}
public class ServiceResponse
{
public string CurrentVersion { get; set; }
public List<string> Folders { get; set; }
public List<Service> Services { get; set; }
}
public class Service
{
public string Name { get; set; }
public string Type { get; set; }
}
注意Enumerable.Select
它将序列的每个元素投影到新表单中。
在您的情况下,servicesList
只是您从该表达式返回的字符串数组。