如何在json格式文件中保存我的treeview复选框状态 [英] How to save my treeview checkbox states in json format file

查看:127
本文介绍了如何在json格式文件中保存我的treeview复选框状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在json格式化文件中保存我添加的树视图父节点和子节点的列表 - test.json。我使用嵌套的foreach循环,但它没有给我正确的保存类型。我的添加方法如下:

  private   void  InitializeTreeView()
{
treeView1.Nodes.Add( new TreeNode( chapter1){Tag = @ \包括{chap1}}); ;
treeView1.Nodes.Add( new TreeNode( chapter2){Tag = @ \ include {chap2}} );
treeView1.Nodes.Add( new TreeNode( chapter3){Tag = @ \ include {chap3}} );
treeView1.Nodes [ 1 ]。Nodes.Add( new TreeNode( sec21){Tag = @ \ input {sec33}});
treeView1.Nodes [ 1 ]。Nodes.Add( new TreeNode( section22){Tag = @ \ input {sec22}});
treeView1.Nodes [ 2 ]。Nodes.Add( new TreeNode( section31){Tag = @ \ input {sec31}});
}





然后我的JSON格式化配置文件如下:



  public   class  DocPart 
{
public string NodeTitle { get ; set ; }
public bool NodeChecked { get ; set ; }
public string ChildTitle { get ; set ; }
public bool ChildChecked { get ; set ; }
}

public class DocConfig
{
public 列表< DocPart>零件{获取; set ; }

public static DocConfig LoadFromString( string jsonData)
{
var serializer = new DataContractJsonSerializer( typeof (DocConfig));

var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData) );
var config =(DocConfig)serializer.ReadObject(ms);

return config;

}
public string SaveToString()
{
var serializer = new DataContractJsonSerializer( typeof (DocConfig));
var ms = new MemoryStream();
serializer.WriteObject(ms, this );
return Encoding.UTF8.GetString(ms.ToArray())。PrettyPrintJson();
}
}



我正在删除不需要的父节点和子节点,并单击复选框。所以我想将复选框状态保存到我的test.json文件中。正如我所说,我已经尝试过嵌套的foreach循环,但它没有给我正确的选择。也许您可以提供一些如何正确保存树视图的提示?我尝试保存:



  private   void  SaveConfig( string  path)
{
var config = new DocConfig();
config.Parts = new 列表< DocPart>();


foreach (TreeNode节点 treeView1.Nodes)
{
{
config.Parts.Add( new DocPart {NodeTitle = node.Text,NodeChecked = node.Checked});
}

foreach (TreeNode child in node.Nodes)
{
config.Parts.Add( new DocPart {ChildTitle = child.Text,ChildChecked = child.Checked});
}
var configString = config.SaveToString();
File.WriteAllText(path,configString);

}
}

解决方案

我不会发布完整的在这里工作代码,因为我为这个场景编写的代码是为客户端完成的。我要发布的是关于如何使用JSON在WinForms TreeView中实现保存/恢复TreeNode的概要。



A.你从一开始建模TreeNode的简单类:

 使用系统; 
使用 System.Collections.Generic;
使用 System.IO;
使用 System.Runtime.Serialization;
使用 System.Runtime.Serialization.Json;
使用 System.Windows.Forms;您的NameSpace中

//

[ DataContract]
public class TNode
{
[DataMember]
public TNode Parent { set ; get ; }

[DataMember]
public string 文字{设置; get ; }

[DataMember]
public string 标记{设置; get ; }

[DataMember]
public bool CState {设置; get ; }

public TNode(TNode parent, string txt, bool cstate, string tag)
{
Parent = parent;
Text = txt;
CState = cstate;
Tag = tag;
}
}

你会注意到这里的节点模型没有子节点列表:这是设计的,并复活正确的父子关系依赖于递归的某种使用。



B.然后,一个将持有TreeNode模型集合的类:pre lang =C#> [DataContract]
public class TNodeCollection
{
[DataMember]
public 列表< TNode> NodeCollection { set ; get ; }

public TNodeCollection(TreeNodeCollection节点)
{
NodeCollection = 列表< TNode>();

// 供您编写
ParseTree ( null ,nodes);
}

// 供您编写
// public void SaveJSON(){...}
// public void RestoreJSON(TreeView电视){...}

// 待续
}

一旦创建了TNodes的平面列表,将它保存为JSON并从JSON中读回来是一件简单的事情。



有趣的是如何从反序列化的平面列表中重新创建正确的父子节点关系。这是通过使用以下事实来实现的:在解析TreeView TreeNodeCollection时使用深度优先递归创建节点模型:由于父节点将在之前创建其子节点,因此我们可以使用TreeNodeCollection。查找(nodename,true)方法,在我们读取子节点时找到父节点,然后设置子节点的父节点。



您的代码在要保存/序列化TreeView的表单可能如下所示:

 TNodeCollection coll =  new  TNodeCollection(treeView1.Nodes); 

coll.SaveJSON();

coll.RestoreJSON(treeView1);


我建​​议使用JSON工具,例如https://codebeautify.org/jsonviewer和https://jsonformatter.org调试,查看和验证JSON数据。


I am trying to save my list of added tree view parents and children nodes in json formated file - test.json. I was using nested foreach loop, but its not giving me right type of my saving. My adding method look like:

private void InitializeTreeView()
{
  treeView1.Nodes.Add(new TreeNode("chapter1") { Tag = @"\include {chap1}" }); ;
  treeView1.Nodes.Add(new TreeNode("chapter2") { Tag = @"\include {chap2}" });
  treeView1.Nodes.Add(new TreeNode("chapter3") { Tag = @"\include {chap3}" });
  treeView1.Nodes[1].Nodes.Add(new TreeNode("sec21") { Tag = @"\input {sec33}" });
  treeView1.Nodes[1].Nodes.Add(new TreeNode("section22") { Tag = @"\input {sec22}" });
  treeView1.Nodes[2].Nodes.Add(new TreeNode("section31") { Tag = @"\input{sec31}" });
}



Then my Document configuration file for JSON formating looks like:

public class DocPart
   {
      public string NodeTitle { get; set; }
      public bool NodeChecked { get; set; }
      public string ChildTitle { get; set; }
      public bool ChildChecked { get; set; }
   }

   public class DocConfig
   {
      public List<DocPart> Parts { get; set; }

       public static DocConfig LoadFromString(string jsonData)
       {
           var serializer = new DataContractJsonSerializer(typeof(DocConfig));

           var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
           var config = (DocConfig)serializer.ReadObject(ms);

           return config;

       }
       public string SaveToString()
       {
           var serializer = new DataContractJsonSerializer(typeof(DocConfig));
           var ms = new MemoryStream();
           serializer.WriteObject(ms, this);
           return Encoding.UTF8.GetString(ms.ToArray()).PrettyPrintJson();
       }
   }


I am removing unwanted parent and children nodes with check boxes click. So I want to save check box state to my test.json file. As I said I have tried nested foreach loop, but it is not giving me right options. Maybe you could offer me some tips how to save my tree view in right way? My try of saving:

private void SaveConfig(string path)
   {
       var config = new DocConfig();
       config.Parts = new List<DocPart>();


       foreach (TreeNode node in treeView1.Nodes)
       {
           {
           config.Parts.Add(new DocPart { NodeTitle = node.Text, NodeChecked = node.Checked });
           }

           foreach (TreeNode child in node.Nodes)
           {
           config.Parts.Add(new DocPart { ChildTitle = child.Text, ChildChecked = child.Checked });
           }
           var configString = config.SaveToString();
           File.WriteAllText(path, configString);

      }
   }

解决方案

I'm not going to post full working code here since the code I have written for this scenario was done for a client. What I am going to post is a general outline for how you can achieve saving/restoring the TreeNodes in a WinForms TreeView using JSON.

A. you start off with a simple class to model a TreeNode:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Windows.Forms;

// in your NameSpace

[DataContract]
public class TNode
{
    [DataMember]
    public TNode Parent { set; get; }

    [DataMember]
    public string Text { set; get; }

    [DataMember]
    public string Tag { set; get; }

    [DataMember]
    public bool CState { set; get; }

    public TNode(TNode parent, string txt, bool cstate, string tag)
    {
        Parent = parent;
        Text = txt;
        CState = cstate;
        Tag = tag;
    }
}

You'll note that the node "model" here has no list of child-nodes: that's by design, and "resurrecting" the correct parent-child relationships is dependent on a certain use of recursion.

B. Then, a Class that will hold the collection of TreeNode "models:"

[DataContract]
public class TNodeCollection
{
    [DataMember]
    public List<TNode> NodeCollection { set; get; }

    public TNodeCollection(TreeNodeCollection nodes)
    {
        NodeCollection = new List<TNode>();

        // for you to write
        ParseTree(null, nodes);
    }

    // for you to write
    //public void SaveJSON() { ... } 
    //public void RestoreJSON(TreeView tv) { ... }

    // to be continued
}

Once you have this "flat list" of TNodes created, it is a simple matter to save that as JSON, and to read it back in, from JSON.

The interesting part is how you recreate from the de-serialized flat list the correct parent-child node relationships. That is achieved by using the fact the node models are created by using depth-first recursion when parsing the TreeView TreeNodeCollection: since Parent Nodes will have been created before their child-nodes, we can use the TreeNodeCollection.Find("nodename", true) method to locate the Parent node as we read the child node, and, then, set the child Node's Parent.

Your code in the Form where you want to save/serialize the TreeView might look like this:

TNodeCollection coll = new TNodeCollection(treeView1.Nodes);

coll.SaveJSON();

coll.RestoreJSON(treeView1);


I would recommend using JSON tools such as https://codebeautify.org/jsonviewer and https://jsonformatter.org to debug, View and validate JSON data.


这篇关于如何在json格式文件中保存我的treeview复选框状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆