Json format and analysis (2)

Usage of Json in Unity



foreword

It may be the first time that many novices have come into contact with Json, and they have no idea what Json is. There are many lectures on the Internet to explain this Json. This article will not go into details here. You can search on Baidu by yourself. If you don’t understand the grammar format, you can refer to my blog Json format and analysis. In this blog, I explained the grammar format of Json and its main usage. You can refer to it. This time I mainly explain the usage and analysis of Json in Unity. I will use a case to explain how we store Json in Unity, and how we read the stored Json.
This article mainly uses LitJson, the download address of LitJson is here


提示:以下是本篇文章正文内容,下面案例可供参考

1. What are the most commonly used Json formats in Unity?

There are two main methods of Json storage that are most commonly used in unity. The first is the LitJson plug-in, and the second is JsonUnility. This JsonUnility is a class created by Unity based on the format of Json storage. It is used for a small amount of data storage. JsonUnility is still very convenient. LitJson is often used to process big data, and its performance is much better than JsonUnility. However, LitJson has a disadvantage that Chinese character conversion fails in some Unity versions. The main reason is that the encoding method of LitJson is UniCode. In this article I will also teach you how to convert to the correct format.

2. Import LitJson into Unity

1. First download LitJson according to the LitJson download address in the preface above

1——After the LitJson download is complete, we open the downloaded file. There is only one file in the file. The dll file should be placed in the Plugins folder, and the namespace should be referenced when accessing code: using LitJson. At this point we need to open the Unity interface, create a new folder under the Assets file and name it Plugins, then return to the folder we downloaded and drag it directly to this folder. Next, we will explain to you how we use it.

2. LitJson stores data

1——First, we create a new class to store our data separately, including our common name, age, address and other data.

The code is as follows (example):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[SerializeField]
public class StudentClass 
{
    
    
    public string _name;
    public string _address;
    public int _age;
}

For the above information, a separate class is written to represent this information, so we don't need to inherit MonoBehaviour, and we don't use the Start and Update functions. This class must add [SerializeField] to make this class an editable parameter.

2——In unity, we set several InputFields to receive the values ​​of these parameters in unity

insert image description here

You can set this information like me, mainly we enter the information in the InputField, and then we click to submit the information to realize storage. Click to read information and we can display the information we just stored in the text box above. The main idea is like this, and you can also set it according to your own ideas. The most important thing is to store the process as I did.
Of course, you also need to set these InputField variables in the UsingLitjson script, and then hang this script on our newly created empty object object GameManger, and then drag and drop the InputField we just created, as shown below
insert image description here

This way we can start our stored procedure

3——Let’s start writing our LitJson storage method

First of all, we need to create a new class named UsingLitJson. In this class, we need to refer to the LitJson namespace Using LitJson, and also introduce our UI namespace. The code is as follows

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using LitJson;

public class UsingLitJson : MonoBehaviour
{
    
    
    public StudentClass studentClass;
    public InputField inputFieldName;
    public InputField inputFieldAge;
    public InputField inputFieldAddress;
    public Text readMassagetext;
    private JsonData jsonData;

    /// <summary>
    /// 给提交按钮添加事件
    /// </summary>
	public void UsingJson()
    {
    
    
        studentClass = new StudentClass();
        studentClass._name = inputFieldName.text;
        studentClass._age = int.Parse(inputFieldAge.text);
        studentClass._address = inputFieldAddress.text;
        jsonData = JsonMapper.ToJson(studentClass);
       Debug.Log(jsonData);
    }
    /// <summary>
    /// 给读取按钮添加事件
    /// </summary>
    public void ReadJson()
    {
    
    
        readMassagetext.text = jsonData.ToString();
    }
}

4 - Add an event to the submit button

insert image description here

5 - Add an event to the read button

insert image description here

6——Run to view the effect

First enter the information and click the submit button to check whether the stored information is correct or not.
insert image description here
From here, you can see that the information has been stored correctly, but the Chinese has not been converted correctly.
Let's take a look at the read information again.
insert image description here
The information is also read correctly. Next, let's take a look at how to set up this Chinese transcoding

7——Chinese conversion format

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using LitJson;
using System;

public class UsingLitJson : MonoBehaviour
{
    
    
    public StudentClass studentClass;
    public InputField inputFieldName;
    public InputField inputFieldAge;
    public InputField inputFieldAddress;
    public Text readMassagetext;
    private JsonData jsonData;

    /// <summary>
    /// 给提交按钮添加事件
    /// </summary>
	public void UsingJson()
    {
    
    
        studentClass = new StudentClass();
        studentClass._name = inputFieldName.text;
        studentClass._age = int.Parse(inputFieldAge.text);
        studentClass._address = inputFieldAddress.text;
        jsonData = JsonMapper.ToJson(studentClass);

        string listJson = jsonData.ToString();
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"(?i)\\[uU]([0-9a-f]{4})");//正则表达式规定格式
        var ss = reg.Replace(listJson,
        delegate (System.Text.RegularExpressions.Match m)
        {
    
    
            return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString();
        });
        Debug.Log(ss);
        
    }
    /// <summary>
    /// 给读取按钮添加事件
    /// </summary>
    public void ReadJson()
    {
    
    
        readMassagetext.text = jsonData.ToString();
    }
}

Adding this piece of code on the original basis can directly convert Chinese successfully.

string listJson = jsonData.ToString();
        System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"(?i)\\[uU]([0-9a-f]{4})");//正则表达式规定格式
        var ss = reg.Replace(listJson,
        delegate (System.Text.RegularExpressions.Match m)
        {
    
    
            return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString();
        });

Summarize

提示:这里对文章进行总结:

This article mainly briefly explains the process of storing information in LitJson. At the same time, we can also write this information directly into our files and other operations are all achievable. In the next issue, I will explain to you how to store and store in a file, and read our information in the file.

Guess you like

Origin blog.csdn.net/m0_45244541/article/details/123939101