"C # Method" Converts an object instance to a JSON string

Source: Internet
Author: User

First, the development reason:

To do a foreground display server file page, want to use the JS control to do, data format using JSON. So just write a directory into a JSON string, but suddenly feel patchwork too verbose, and customization is too high, not flexible, so simply write the C # DirectoryInfo instances recursively find all subfolders and files, and then output into a JSON string.

Next, many C # data models are found to be the same structure, such as sites and subsites in SharePoint, where each site has a list or document library. Then why not expand it.

Second, the basic principle:

Use Type.InvokeMember () to execute the method and get properties of the instance.

 string  path = @ " e:\work\test   ;D Irectoryinfo 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"nullnewObject[] {});

Third, all code:

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.IO;usingSystem.Reflection;namespacegetfolderjsondata{classProgram { 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 stringResultjson =""; Static voidMain (string[] args) {            stringPath =@"E:\Work_28528033\test"; DirectoryInfo Foldera=NewDirectoryInfo (path); stringDD ="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 voidWrite () {FileStream fs=NewFileStream (@"E:\Work_28528033\result.txt", FileMode.Create); //get byte array            byte[] data =System.Text.Encoding.Default.GetBytes (Resultjson); //Start WritingFs. Write (data,0, data.            Length); //empties the buffer, closes the streamFS.            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 stringGetjsondatafromobject (Objectfolder) {Type type=folder.            GetType (); intDiguiint =-1; foreach(stringZijimethodsiteminchzijimethods) {Diguiint++; Object[] Folders = (Object[]) type. InvokeMember (Zijimethodsitem, Bindingflags.default | BindingFlags.InvokeMethod,NULL, folder,New Object[] { }); if(folders. Length>0) {Resultjson+ = Zijinames[diguiint] +":["; foreach(ObjectDirinchfolders) {Resultjson+="{"; Type Diguitype=dir.                        GetType (); foreach(stringZijinamesiteminchzijifields) {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+="],"; }            }            intFushumethodsint =-1; foreach(stringFushumethodsiteminchfushumethods) {Fushumethodsint++; Object[] files = (Object[]) type. InvokeMember (Fushumethodsitem, Bindingflags.default | BindingFlags.InvokeMethod,NULL, folder,New Object[] { }); if(Files. Length>0) {Resultjson+=fushunames[fushumethodsint] +":["; foreach(ObjectFileiteminchfiles) {Resultjson+="{"; Type Protype=Fileitem.gettype (); foreach(stringFushufieldsiteminchfushufields) {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+="]"; }            }            returnResultjson; }    }}

Conclusion:

Http://www.bejson.com/JSON Formatting tool (a random search, not necessarily the best)

Use:

The Ziji represents the same as the incoming type.

Fushu represents an instance of another type that this type instance contains.

field is fields.

Name is the name that is displayed in the JSON. Name corresponds to method.

If you still can not understand it is too normal, make a folder for yourself to try it.

Attach test folder, project code, get results:

{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", Exten Sion: ". txt"}]}], Files: [{Name: "1.1.txt", Exte Nsion: ". txt"}, {Name: "1.2.txt", Extension: ". txt"}, {Na Me: "1.3.txt", Extension: ". txt"}]}

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

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

"C # Method" Converts an object instance to a JSON string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.