Guide to converting data from XML to Json in Unity

Tram Ho

Hello friends!

As the title, I will guide you to convert data from XML to JSON! The problem is related to the input data provided to our customers, but managing and storing xml is difficult, so we will convert it via json for easy play!

Ok, got it on the job!

Step 1: Import XML.

  • You can find any XML file on the internet, find something basic or something less data for a bit of practice, master, then play anything: v.
  • You drag it into your Unity project, the newly created project is also easy to see.
  • You put it in the folder “Assets / Resources / XML / data.txt” (txt or xml extension does not matter, I left txt open it to help open the brower only)

Sample XML you can use temporarily in this article:

Step 2: Create Script DataGame.cs

  • You create a file named DataGame.cs in Unity.
  • The task of this file is to read the data from the above XML file, then save its value as an object, then we convert from the object to json, and finally save it as a file.

Step 3: Add Component.

  • You add the above DataGame.cs to an object on any scene, such as Camera, this helps it to be run when we press play game.
  • If this script is not run, conversion cannot be performed.

Step 4: Read XML.

  • You open the DataGame.cs file and then write the following code:

  • So we have the data we need, but it is still in xml form.

Step 5: Define Object.

  • As you can see above, we have data inside the chapter that are pages, inside pages with number, with names, with dialogue.
  • So we will declare two classes to define the object as follows:

  • Then you declare ChapterData inside DataGame as follows:

Step 6: Convert XML to Object.

  • This step you will convert data from XML into Objects.
  • You write the following code:

Step 7: Convert Object to Json and save to file.

  • You write the following code:

So you have successfully converted from the XML file to a Json file, in addition to you have successfully declared the object in Unity, the rest later is to call up the json file and use it normally without using the file. XML again!

I wish you success! ^ _ ^

Share the news now

Source : Viblo