How to display JSON in WPF TreeView

后端 未结 3 1213
感情败类
感情败类 2020-12-18 15:54

I am reading in JSON and then displaying it in a WPF treeview.

Here is the code...

Class MainWindow
Public Sub New()

    InitializeComponent()
    D         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-18 16:55

    I needed a more generic operation to consume any JSON.

    This code uses the nuget Newtonsoft JSON to do the magic of taking any raw JSON (without models) and loading it into a TreeView which looks like this:

    JSON

    string jsonString = @"[{""BatchId"":0,""AccessionChanges"":[{""LabId"":8675309,""InstanceChanges"":[{""Property"":""Note"",""ChangedTo"":""Jabberwocky"",""UniqueId"":null,""SummaryInstance"":null},{""Property"":""Instrument"",""ChangedTo"":""instrumented"",""UniqueId"":null,""SummaryInstance"":null}],""DetailChanges"":[{""Property"":""Comments"",""ChangedTo"":""2nd Comment"",""UniqueId"":null,""SummaryInstance"":null},{""Property"":""CCC"",""ChangedTo"":""XR71"",""UniqueId"":null,""SummaryInstance"":null}]}]}]";

    Xaml

    Codbehind Xaml

    InitializeComponent();
    try
    {
        tView.Items.Add(JSONOperation.Json2Tree(JArray.Parse(jsonString), "Root"));    
    }
    catch (JsonReaderException jre)
    {
        MessageBox.Show($"Invalid Json {jre.Message}");
    }
    

    public static class JSONOperation

    public static TreeViewItem Json2Tree(JToken root, string rootName = "")
    {
        var parent = new TreeViewItem() { Header = rootName };
    
        foreach (JToken obj in root)
            foreach (KeyValuePair token in (JObject)obj)
                switch (token.Value.Type)
                {
                    case JTokenType.Array:
                        var jArray = token.Value as JArray;
    
                        if (jArray?.Any() ?? false)
                            parent.Items.Add(Json2Tree(token.Value as JArray, token.Key));
                        else
                            parent.Items.Add($"\x22{token.Key}\x22 : [ ]"); // Empty array   
                        break;
    
                    case JTokenType.Object:
                        parent.Items.Add(Json2Tree((JObject)token.Value, token.Key));
                        break;
    
                    default:
                        parent.Items.Add(GetChild(token));
                        break;
                }
    
        return parent;
    }
    
    private static TreeViewItem GetChild(KeyValuePair token)
    {
        var value = token.Value.ToString();
        var outputValue = string.IsNullOrEmpty(value) ? "null" : value;
        return new TreeViewItem() { Header = $" \x22{token.Key}\x22 : \x22{outputValue}\x22"}; 
    }
    

提交回复
热议问题