从JSON

时间:2017-07-24 18:50:47

标签: c# json json.net treeview

我可以将REST JSON加载到数组中。但我需要将数据加载为词典以访问nametype,以便在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);
}

喜欢:

enter image description here

但我需要像

这样的东西

enter image description here

我已经像这样添加了字典

Dictionary<string, string> dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

bot不确定如何从那里检索数据并应用于treeView1

1 个答案:

答案 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只是您从该表达式返回的字符串数组。