VB.net saving JSON-formatted strings to an XML file

Source: Internet
Author: User

1. About this article

These days, I'm going to write a tool class Jsonxmlhelper for working with XML to save JSON-formatted files. The 2 most important functions are implemented in the tool class:

1) Write the contents of the JSON format to the address in XML: Writejsontoxml

2) Restore the XML file constructed in function 1 to the JSON format document: Recoverjsonfromxml

The implementation of function 1 will be given in this article, the implementation of function 2 will be published later in the blog post given

2. Code description

1) Add Reference: Newtonsoft.Json.dll

2) Import Library

' Json parsing correlation function, need to add reference Newtonsoft.Json.dllImports newtonsoft.jsonimports Newtonsoft.Json.Linq ' XML parse related function imports System.Xml

3) Create Class Jsonxmlhelper in the module moduletest

4) Two basic functions:

WriteToFile (writes the contents of a string to a file)

ReadFromFile (reading content from a file is assigned to a string)

'  <summary> '   writes the contents of the string to the file '  </summary> '  <param name= ' address ' > File Address </param> '  <param name= ' content > The string being written to the file </param> ' '  <remarks ></remarks>public shared sub writetofile (address as string, content  as string) &NBSP;&NBSP;&NBSP;&NBSP;TRY&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;DIM&NBSP;SW  as io. Streamwriter        sw = new io. StreamWriter (Address, false, system.text.encoding.utf8)         &NBSP;SW. Write (content)         sw. Close ()         sw. Dispose ()     Catch ex As Exception         throw new exception (ex. Message)     end tryend sub '  <summary>‘‘‘   Reading information from a file to the string '  </summary> ' '  <param name= ' address > file Addresses </param> '  <returns> read the string </returns> '  <remarks></remarks>Public Shared  Function readfromfile (address as string)     Try         dim sr as io. Streamreader        sr = io. File.OpenText (address)         return sr. ReadToEnd ()     Catch ex As Exception         throw new exception (ex. Message)     end tryend function

'  <summary> '   writes JSON-formatted content to XML '  </summary> '  <param  ' in address ' Name= "Address" > file addresses to be deposited </param> '  <param name= ' json ' > Source JSON string </param> ' '   <remarks></remarks>public shared sub writejsontoxml (Address As String,  json as string)      ' If there is a file with the same name, delete     if io first. File.exists (address)  then        io. File.delete (address)     End If     ' building an XML document      dim writer as xmltextwriter =        new  xmltextwriter (address, text.encoding.getencoding ("GBK"))     writer. Formatting = xml.formatting.indented    writer. WriteStartDocument ()     writer. WriteComment ("This XML document stores a JSON-formatted message") &NBSP;&NBSP;&Nbsp;  ' recursively iterates through the items in the JSON and writes to the XML in     writer. WriteStartElement ("Root")      ' writes the contents of the JSON string to the XML document     writetoxml (writer ,  json)     writer. WriteEndElement ()   ' root node ends     writer. WriteEndDocument ()     writer. Close ()      ' XML document creation end End sub '  <summary> '   writing a JSON format string to an XML file '  </summary> " <param name=" writer "></param>"  <param name= " JSON "></param>"  <remarks></remarks>private shared sub writetoxml ( writer as xmltextwriter, json as string)     dim jobj as  jobject = jobject.parse (JSON)      ' traversal of the JSON string read to     for  each jtemp as jproperty in jobj. children         ' according to the different data read inType classification Discussion          ' Console.WriteLine (jtemp. name.tostring &  " "  & jtemp. value.tostring)         select case jtemp. Value.type            case jtokentype.object                 writer. WriteStartElement (jtemp. Name.tostring (),  "")                  writer. WriteAttributeString ("Type",  "Object")                  writetoxml (writer, jtemp. value.tostring)                  writer. WriteEndElement ()             Case  Jtokentype.array&nbSp;               writer. WriteStartElement (jtemp. Name.tostring (),  "")                  writer. WriteAttributeString ("Type",  "Array")                   ' traversal array Read value                  for i as integer = 0 to jtemp. value.count - 1                     writer. WriteAttributeString ("Value"  & i, jtemp. Value (i). ToString)                 next                 writer. WriteendeLement ()             case jtokentype.string                 writer. WriteStartElement (jtemp. Name.tostring (),  "")                  writer. WriteAttributeString ("Type",  "String")                  writer. WriteAttributeString ("Value",  jtemp. value.tostring)                  writer. WriteEndElement ()             Case  jtokentype.boolean                 writer. WriteStartElement (jtemp. Name.tostring (),  "")           &nbsP;     writer. WriteAttributeString ("Type",  "Boolean")                  writer. WriteAttributeString ("Value",  jtemp. value.tostring)                  writer. WriteEndElement ()             Case  jtokentype.integer                 writer. WriteStartElement (jtemp. Name.tostring (),  "")                  writer. WriteAttributeString ("Type",  "Integer")                  writer. WriteAttributeString ("Value",  jtemp. value.tostring) &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;  writer. WriteEndElement ()             Case  jtokentype.float                 writer. WriteStartElement (jtemp. Name.tostring (),  "")                  writer. WriteAttributeString ("Type",  "Float")                  writer. WriteAttributeString ("Value",  jtemp. value.tostring)                  writer. WriteEndElement ()             Case  jtokentype.null                 writer. WriteStartElement (jtemp. Name.tostring (),  "")       &Nbsp;         writer. WriteAttributeString ("Type",  "Null")                  writer. WriteAttributeString ("Value",  jtemp. value.tostring)                  writer. WriteEndElement ()             Case Else         end select    nextend sub

3. Example of invocation of several functions above

1) Building a structure person

public class person    public name as string  ' name      Public Age As Integer  ' Age     Public Sex_is_Male  as boolean  ' Gender     Public Structure PartnerInfo  ' partner information structure          Public Partner_Name As String  ' Partner name          Public Partner_Age As Integer  ' partner Age          Public Partner_Sex_is_Male As Boolean  ' partner Sex      End Structure    Public Partner As PartnerInfo  ' Partners     public achievement as string ()      " < summary>     '   Constructors      '  </summary>      '  <param name= "IsDefault" >true: Use default value, false: Use test value </param>     ' '  <remarks> </remarks>    public sub new (Optional byval isdefault as  boolean = true)         me.name = iif ( isdefault,  "",  "Tsybius")         me.age = iif ( isdefault, 0, 23)         me.sex_is_male = iif ( Isdefault, true, true)         me.partner.partner_name =  iif (isdefault,  "",  "Galatea")          Me.partner.partner_age = iif (isdefault, 0, 21)          me.partner.partner_sex_is_male = iif (Isdefault, true, false)          me.achievement =&nBsp;iif (isdefault, new string ()  {},             new string ()  {"Ach1",  "Ach2",  "Ach3"})     end subend  class

2) calls the functions in this article in the main function

Sub main ()      ' write test contents to file Test.txt     jsonxmlhelper.writetofile (" Test.txt ", " This is a test content ")      ' read the content from the file Test.txt     console.writeline ( Jsonxmlhelper.readfromfile ("Test.txt"))     console.writeline ()      ' Create a person structure instance     dim p as person = new person (False)       ' Store the person type instance in a JSON-formatted string (two formats: do not indent, indent)     Dim json1 As  String =        jsonconvert.serializeobject (p,  Newtonsoft.Json.Formatting.None)     Dim json2 As String =         jsonconvert.serializeobject (p, newtonsoft.json.formatting.indented)      ' output-generated string     console.writeline (json1 & vbcrlf  & vbCrLf & Json2)     jsonxmlhelper.writejsontoxml ("X.xml",  json1)      Console.ReadLine () end sub

3) Running Results

Console output Results

The generated x.xml content

<?xml version= "1.0" encoding= "gb2312"?><!--This XML document stores a JSON-formatted message--><root> <name type= "String "Value=" Tsybius "/> <age type=" Integer "value=" All "/> <sex_is_male type=" Boolean "value=" True "/> <p Artner type= "Object" > <partner_name type= "String" value= "Galatea"/> <partner_age type= "Integer" value= " "/> <partner_sex_is_male type=" Boolean "value=" False "/> </Partner> <achievement type=" Array "Va lue0= "Ach1" value1= "Ach2" value2= "Ach3"/></root>

END

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.