[Daily of Unity3D] Unity writes Json data, and reads and parses Json data in Unity

I. Introduction

In daily development, you will encounter the need to save data or send data. Data storage is usually Json or XML. Today we will look at how to read and write Json data in Unity, and parse Json data, including multi-segment data. Parsing

2. Reading, writing and parsing of a single Json data

1. Writing a single piece of Json data

First, we first write a field class Person, which has a string type "Name" and an int type "Grade", and then write a "Data" data class, which stores our field class Person:

[System.Serializable]
class Person
{
    public string Name;
    public int Grade;
}
[System.Serializable]
class Data
{
    public Person Person;
}

The first is to write Json data:

	//写数据
    public void WriteData()
    {
    	//新建一个字段类 进行赋值
        Person m_Person = new Person();
        m_Person.Name = "User1";
        m_Person.Grade = 13;
        //新建一个数据类 将字段类赋值
        Data m_Data = new Data();
        m_Data.Person = m_Person;
        //将数据转成json
        string js = JsonUtility.ToJson(m_Data);
        //获取到项目路径
        string fileUrl = Application.streamingAssetsPath + "\\jsonInfo2.txt";
        //打开或者新建文档
        StreamWriter sw = new StreamWriter(fileUrl);
        //保存数据
        sw.WriteLine(js);
        //关闭文档
        sw.Close();
    }

Yes, you have to create a new StreamingAssets folder, otherwise you will get an error: the
Insert picture description here
data is as follows:
Insert picture description here
there is no problem with the website analysis:
Insert picture description here

2. Reading a single piece of Json data

Reading is very simple:

	//读取文件
    public string ReadData()
    {
    	//string类型的数据常量
        string readData = "";
        //获取到路径
        string fileUrl = Application.streamingAssetsPath+ "\\jsonInfo2.txt";
        //读取文件
        StreamReader str = File.OpenText(fileUrl);
        //数据保存
        readData = str.ReadToEnd();
        str.Close();
        //返回数据
        return readData;
    }

Come, let's get the data to see if it is right:

	void Start()
    {
        string jsonData = ReadData();
        Debug.Log(jsonData);
    }

Look at the console output:
Insert picture description here

3. Analysis of a single Json data

	void Start()
    {
        string jsonData = ReadData();
        Debug.Log(jsonData);
        //数据解析并把数据保存到m_PersonData变量中
		Data m_PersonData = JsonUtility.FromJson<Data>(jsonData);
		//读取数据
        Debug.Log(m_PersonData.Person.Name);
        Debug.Log(m_PersonData.Person.Grade);
    }

Insert picture description here
The complete code is as follows:

using System.IO;
using UnityEngine;

[System.Serializable]
class Person
{
    public string Name;
    public int Grade;
}
[System.Serializable]
class Data
{
    public Person Person;
}

public class TestToJson : MonoBehaviour
{
    void Start()
    {
        //WriteData();
        string jsonData = ReadData();
        Debug.Log(jsonData);

        Data m_PersonData = JsonUtility.FromJson<Data>(jsonData);
        Debug.Log(m_PersonData.Person.Name);
        Debug.Log(m_PersonData.Person.Grade);
    }


    //读取文件
    public string ReadData()
    {
        string readData = "";
        string fileUrl = Application.streamingAssetsPath+ "\\jsonInfo2.txt";
        StreamReader str = File.OpenText(fileUrl);
        readData = str.ReadToEnd();
        str.Close();
        return readData;
    }

    //写数据
    public void WriteData()
    {
        Person m_Person = new Person();
        m_Person.Name = "User1";
        m_Person.Grade = 13;
        Data m_Data = new Data();
        m_Data.Person = m_Person;
        string js = JsonUtility.ToJson(m_Data);
        string fileUrl = Application.streamingAssetsPath + "\\jsonInfo2.txt";
        StreamWriter sw = new StreamWriter(fileUrl);
        sw.WriteLine(js);
        sw.Close();
    }
}

Three, read and write, analysis of multiple Json data

1. Writing multiple Json data

First of all, we first write a field class Person, which has the string type "Name" and int type "Grade", and then write a "Data1" data class, which stores our field class Person array:

[System.Serializable]
class Person
{
    public string Name;
    public int Grade;
}
[System.Serializable]
class Data1
{
    public Person[] Person;
}

The first is to write Json data:

	//写数据
    public void WriteData()
    {
        //新建一个数据类
        Data1 m_Data = new Data1();
        //新建一个字段类 进行赋值
        m_Data.Persons = new Person[5];
        for (int i = 0; i < 5; i++)
        {
            Person m_Person = new Person();
            m_Person.Name = "User" + i;
            m_Person.Grade = i + 50;
            m_Data.Persons[i] = m_Person;
        }
        //将数据转成json
        string js = JsonUtility.ToJson(m_Data);
        //获取到项目路径
        string fileUrl = Application.streamingAssetsPath + "\\jsonInfo3.txt";
        //打开或者新建文档
        StreamWriter sw = new StreamWriter(fileUrl);
        //保存数据
        sw.WriteLine(js);
        //关闭文档
        sw.Close();
    }

Yes, you have to create a new StreamingAssets folder, otherwise you will get an error: the
Insert picture description here
data is as follows:
Insert picture description here
there is no problem with the website analysis:
Insert picture description here

2. Reading multiple Json data

Reading is very simple:

	//读取文件
    public string ReadData()
    {
    	//string类型的数据常量
        string readData = "";
        //获取到路径
        string fileUrl = Application.streamingAssetsPath+ "\\jsonInfo3.txt";
        //读取文件
        StreamReader str = File.OpenText(fileUrl);
        //数据保存
        readData = str.ReadToEnd();
        str.Close();
        //返回数据
        return readData;
    }

Come, let's get the data to see if it is right:

	void Start()
    {
        string jsonData = ReadData();
        Debug.Log(jsonData);
    }

Look at the console output:
Insert picture description here

3. Analysis of multiple Json data

	void Start()
    {
        string jsonData = ReadData();
        Debug.Log(jsonData);
        //数据解析并把数据保存到m_PersonData1 变量中
        Data1 m_PersonData1 = JsonUtility.FromJson<Data1>(jsonData);
        foreach (var item in m_PersonData1.Persons)
        {
            Debug.Log(item.Name);
            Debug.Log(item.Grade);
        }
    }

Insert picture description here
The complete code is as follows:

using System.IO;
using UnityEngine;

[System.Serializable]
class Person
{
    public string Name;
    public int Grade;
}
[System.Serializable]
class Data
{
    public Person Person;
}
[System.Serializable]
class Data1
{
    public Person[] Persons;
}

public class TestToJson : MonoBehaviour
{
    void Start()
    {
        //WriteData2();
        //WriteData3();
        
		//单条数据
        //string jsonData = ReadData();
        //Debug.Log(jsonData);
        //Data m_PersonData = JsonUtility.FromJson<Data>(jsonData);
        //Debug.Log(m_PersonData.Person.Name);
        //Debug.Log(m_PersonData.Person.Grade);

		//多条数据
        string jsonData = ReadData();
        Debug.Log(jsonData);
        Data1 m_PersonData1 = JsonUtility.FromJson<Data1>(jsonData);
        foreach (var item in m_PersonData1.Persons)
        {
            Debug.Log(item.Name);
            Debug.Log(item.Grade);
        }
    }


    //读取文件
    public string ReadData()
    {
        string readData = "";
        string fileUrl = Application.streamingAssetsPath+ "\\jsonInfo3.txt";
        StreamReader str = File.OpenText(fileUrl);
        readData = str.ReadToEnd();
        str.Close();
        return readData;
    }

    //写数据
    public void WriteData2()
    {
        Person m_Person = new Person();
        m_Person.Name = "User1";
        m_Person.Grade = 13;
        Data m_Data = new Data();
        m_Data.Person = m_Person;
        string js = JsonUtility.ToJson(m_Data);
        string fileUrl = Application.streamingAssetsPath + "\\jsonInfo2.txt";
        StreamWriter sw = new StreamWriter(fileUrl);
        sw.WriteLine(js);
        sw.Close();
    }

    //写数据
    public void WriteData3()
    {
        Data1 m_Data = new Data1();
        m_Data.Persons = new Person[5];
        for (int i = 0; i < 5; i++)
        {
            Person m_Person = new Person();
            m_Person.Name = "User" + i;
            m_Person.Grade = i + 50;
            m_Data.Persons[i] = m_Person;
        }
        string js = JsonUtility.ToJson(m_Data);
        string fileUrl = Application.streamingAssetsPath + "\\jsonInfo3.txt";
        StreamWriter sw = new StreamWriter(fileUrl);
        sw.WriteLine(js);
        sw.Close();
    }
}

Summary:
1. Do n’t write your own json string, otherwise a bracket or curly bracket will be wrong and you wo n’t
be able to solve it . 2. You need to know the format of the json string you receive, and then write your own data class
3. If it ’s not involved If the server data is all local data, it is best to write it yourself

Published 226 original articles · praised 509 · 530,000 views

Guess you like

Origin blog.csdn.net/q764424567/article/details/101448124