zoukankan      html  css  js  c++  java
  • 【C#方法】将对象实例转化为JSON字符串

    第一、开发原因:

    要做一个前台显示服务器文件的网页,想用JS控件做,数据格式使用JSON。所以就写将某目录转化成JSON字符串,但是突然觉得拼凑太啰嗦,而且定制化太高,不灵活,所以索性就写将C#中的DirectoryInfo实例递归下去找到所有子文件夹和文件,然后输出成JSON字符串。

    紧接着,发现很多C#数据模型都是一样的结构,比如SHarepoint中的网站和子网站,每个网站有列表或文档库。那何不扩展一下呢。

    第二、基本原理:

    使用Type.InvokeMember()执行实例的方法和取得属性。

    string path = @"E:Work	est";
    DirectoryInfo folder = new DirectoryInfo(path);
    Type type = foldera.GetType();
    FileInfo[] files = (FileInfo[])type.InvokeMember("GetFiles", BindingFlags.Default | BindingFlags.InvokeMethod, null, folder, new object[] { });
    String Name = (String)type.InvokeMember("Name", BindingFlags.Default | BindingFlags.GetProperty, null, folder, new object[] { });

    第三、全部代码:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Reflection;
    
    namespace GetFolderJsonData
    {
        class Program
        {
            public static string[] ZIJINames = new string[] { "Folder" };
            public static string[] FUSHUNames = new string[] { "Files" };
            public static string[] ZIJIMethods = new string[] { "GetDirectories" };
            public static string[] FUSHUMethods = new string[] { "GetFiles" };
            public static string[] ZIJIFields = new string[] { "Name" };
            public static string[] FUSHUFields = new string[] { "Name", "Extension" };
            public static string resultJson = "";
    
            static void Main(string[] args)
            {
                string path = @"E:Work_28528033	est";
                DirectoryInfo foldera = new DirectoryInfo(path);
                string dd = "GetFiles";
                Type type = foldera.GetType();
                FileInfo[] files = (FileInfo[])type.InvokeMember(dd, BindingFlags.Default | BindingFlags.InvokeMethod, null, foldera, new object[] { });
                resultJson += "{";
                GetJsonDataFromObject(foldera);
                resultJson += "}";
                Write();
    
            }
    
            public static void Write()
            {
                FileStream fs = new FileStream(@"E:Work_28528033
    esult.txt", FileMode.Create);
                //获得字节数组
                byte[] data = System.Text.Encoding.Default.GetBytes(resultJson);
                //开始写入
                fs.Write(data, 0, data.Length);
                //清空缓冲区、关闭流
                fs.Flush();
                fs.Close();
            }
            
            //public static string GetJsonData(string path)
            //{
            //    string resultJson="[{";
            //    DirectoryInfo folder = new DirectoryInfo(path);
            //    if (folder.GetDirectories().Length > 0)
            //    {
            //        resultJson += "Folder:";
            //        foreach (DirectoryInfo f in folder.GetDirectories())
            //        {
            //            resultJson += "";
            //            GetJsonData(folder.FullName);
            //        }
            //        resultJson += "";
            //    }
            //    if (folder.GetFiles().Length>0)
            //    {
            //        resultJson += "";
            //        foreach (FileInfo file in folder.GetFiles())
            //        {
            //            resultJson += "";
            //        }
            //        resultJson += "";
            //    }
            //    return resultJson += "}]";
            //}
            
    
            public static string GetJsonDataFromObject(object folder) 
            {
                Type type = folder.GetType();
                int diguiInt = -1;
                foreach (string ZIJIMethodsItem in ZIJIMethods)
                {
                    diguiInt++;
                    object[] folders = (object[])type.InvokeMember(ZIJIMethodsItem, BindingFlags.Default | BindingFlags.InvokeMethod, null, folder, new object[] { });
                    if (folders.Length>0)
                    {
                        resultJson += ZIJINames[diguiInt] + ":[";
                        foreach (object dir in folders)
                        {
                            resultJson += "{";
                            Type diguiType = dir.GetType();
                            foreach (string ZIJINamesItem in ZIJIFields)
                            {
                                resultJson += ZIJINamesItem+":"";
                                resultJson += diguiType.InvokeMember(ZIJINamesItem, BindingFlags.Default | BindingFlags.GetProperty, null, dir, new object[] { }).ToString()+"",";
                            }
                            GetJsonDataFromObject(dir);
                            resultJson += "},";
                        }
                        resultJson = resultJson.Substring(0, resultJson.Length - 1);
                        resultJson += "],";
                    }
                }
                int FUSHUMethodsInt = -1;
                foreach (string FUSHUMethodsItem in FUSHUMethods)
                {
                    FUSHUMethodsInt++;
                    object[] files = (object[])type.InvokeMember(FUSHUMethodsItem, BindingFlags.Default | BindingFlags.InvokeMethod, null, folder, new object[] { });
                    if (files.Length>0)
                    {
                        resultJson +=FUSHUNames[FUSHUMethodsInt] + ":[";
                        foreach (object fileItem in files)
                        {
                            resultJson += "{";
                            Type proType = fileItem.GetType();
                            foreach (string FUSHUFieldsItem in FUSHUFields)
                            {
                                resultJson += FUSHUFieldsItem + ":"";
                                resultJson += proType.InvokeMember(FUSHUFieldsItem, BindingFlags.Default | BindingFlags.GetProperty, null, fileItem, new object[] { }).ToString() + "",";
                            }
                            resultJson = resultJson.Substring(0, resultJson.Length - 1);
                            resultJson += "},";
                        }
                        resultJson = resultJson.Substring(0, resultJson.Length - 1);
                        resultJson += "]";
                    }
                }
                return resultJson;
            }
        }
    }

    结束语:

    http://www.bejson.com/  JSON格式化工具(随便搜了一个,不一定是最好的)

    使用:

    ZIJI代表与与传入类型相同。

    FUSHU代表这种类型实例包含的另外一种类型的实例。

    Field是字段。

    Name是显示在JSON中的名字。Name与Method相对应。

    如果还是看不懂那太正常了,自己做一个文件夹试试吧。

    附上测试文件夹,工程代码,得到结果:

    {
        Folder: [
            {
                Name: "1.1F",
                Folder: [
                    {
                        Name: "1.1.1F",
                        Files: [
                            {
                                Name: "1.1.1.1 (1).txt",
                                Extension: ".txt"
                            },
                            {
                                Name: "1.1.1.1 (2).txt",
                                Extension: ".txt"
                            },
                            {
                                Name: "1.1.1.1.txt",
                                Extension: ".txt"
                            }
                        ]
                    }
                ],
                Files: [
                    {
                        Name: "1.1.1.txt",
                        Extension: ".txt"
                    },
                    {
                        Name: "1.1.2.txt",
                        Extension: ".txt"
                    },
                    {
                        Name: "1.1.3.txt",
                        Extension: ".txt"
                    }
                ]
            },
            {
                Name: "1.2F",
                Files: [
                    {
                        Name: "1.2.1.txt",
                        Extension: ".txt"
                    },
                    {
                        Name: "1.2.2.txt",
                        Extension: ".txt"
                    },
                    {
                        Name: "1.2.3.txt",
                        Extension: ".txt"
                    }
                ]
            }
        ],
        Files: [
            {
                Name: "1.1.txt",
                Extension: ".txt"
            },
            {
                Name: "1.2.txt",
                Extension: ".txt"
            },
            {
                Name: "1.3.txt",
                Extension: ".txt"
            }
        ]
    }

    http://files.cnblogs.com/files/yixiaozi/GetFolderJsonData.rar

    http://files.cnblogs.com/files/yixiaozi/GetFolderJsonDatatestFolder.rar

  • 相关阅读:
    day10 测试2
    算法题
    day10 自动化测试
    day09 测试
    进行试验,对比
    多层网络的SIR实现
    day08 商城项目
    day07 cookie session 模板
    day06 模型类
    纸上谈兵:图(graph)
  • 原文地址:https://www.cnblogs.com/yixiaozi/p/4506202.html
Copyright © 2011-2022 走看看