当前位置:网站首页>Unity's data persistence -- Jason
Unity's data persistence -- Jason
2022-06-11 03:25:00 【Go_ Accepted】
1、Json What is it?
JavaScript Object shorthand (JavaScript Object Notation)
json It is an international lightweight data exchange format , It is mainly used to transmit data in network communication , Or local data storage and reading , Easy to read and write , At the same time, it is also easy for machine analysis and generation , And effectively improve the network transmission efficiency
The game data can be divided into Json The standard format is stored in Json In the document , then Json The document is stored on the hard disk or transmitted to the remote , To achieve the purpose of data persistence or data transmission
Json and Xml Similarities and differences :
Common ground : It's all plain text , Have a hierarchy , Are descriptive
Difference :Json Simpler configuration ,Json In some cases, it is faster to read and write
2、 edit Json How to file
(1) System comes with —— Notepad 、 Writing board
(2) General text editor ——Sublime Text etc.
(3) Webpage Json Editor
I use it vs code, You can edit json file
3、 Basic grammar
Annotation and C# The annotation method is the same in , But it needs to be set to ”Json with Comments“ In the form of ( stay vs code Set in the lower right corner )
Rule of grammar :
Symbolic meaning :
| Curly braces {} | object |
| brackets [] | Array |
| The colon : | Key value pair correspondence |
| comma , | Data segmentation |
| Double quotes “” | Key name / character string |
| Value type | Numbers ( Integer or floating point )、 character string 、true or false、 Array 、 object 、null |
Json Format is a key value pair structure , Expressed as :“ Key name ”: Value content
With C# Code, for example :
class ClassInfo {
public string name;
public int age;
public bool sex;
public List<int> ids;
public List<Person> students;
public Home home;
public Person son;
}
class Person {
public string name;
public int age;
public bool sex;
}
class Home {
public string address;
public string street;
}take ClassInfo Class to Json The format is :
// Braces wrap an object
{
// The colon represents the correspondence of key value pairs
// A comma is a separator that separates member variables
// Json The key in the middle must be enclosed in double quotation marks , Whether the value is quoted in double quotation marks depends on the type
"name": "Waylon",
"age": 18,
"sex": true,
"testF": 1.4, // Used to test support for floating point types
// Brackets represent arrays
"idx": [1,2,3,4],
"students": [
{"name": "Hong", "age": 5, "sex": false},
{"name": "Ming", "age": 6, "sex": true},
{"name": "Qiang", "age": 8, "sex": true}
// Be careful : Don't add commas to the last item , Otherwise, parsing may cause problems !!!
],
"home": {
"address": "Cheng",
"street": "Chun"
},
"son": null
}
Key to dictionary ( Numbers ) Will become a double quoted string , Attention should be paid to !!!
“dic":{“1”:“123”,“key":{"id":1, "num": 3}}meanwhile ,Json It won't be right private, protected Explain
4、Excel turn Json
For the time being, you can use the online conversion tool :https://www.bejson.com/json/col2json/
then 【 download Json Code 】, The conversion result may not be accurate
5、JsonUtility serialize
(1)、JsonUtility What is it?
JsonUtility yes Unity The built-in is used for parsing Json The public class of , It can :
i、 Serialize an in memory object as Json Format string
ii、 take Json The string is deserialized into a class object
(2) Save and read a string in a file
i、 Store the string in the specified path file
// Parameter one : Storage path
// Must be an existing file path , If there is no corresponding folder , Will report a mistake
// Parameter two : Stored string contents
File.WriteAllText(Application.streamingAssetsPath+ "/Test.json", " Test stored json file ");
// If Json If the folder does not exist, an error will be reported
// File.WriteAllText(Application.streamingAssetsPath+ "/Json/Test.json", " Test stored json file ");ii、 Read the string in the specified path file
// Parameter one : Read path
// Parameter two : Coding format ( Optional )
string str = File.ReadAllText(Application.streamingAssetsPath+ "/Test.json");(3) Use JsonUtility serialize
Serialization is to store the data in memory on the hard disk , The way is through API:JsonUtility.ToJson( object )
Take the following class objects for example :
class Student {
public int age;
public string name;
public Student(int age, string name) {
this.age = age;
this.name = name;
}
}
class Person {
public string name;
public int age;
public bool sex;
public float testF;
public double testD;
public int[] ids;
public List<int> ids2;
public Dictionary<int, string> dic;
public Dictionary<string, string> dic2;
public Student s1;
public List<Student> s2;
private int privateI = 1;
protected int protectedI = 2;
}Then serialize the data class
Person p = new Person();
p.name = "Well";
p.age = 19;
p.sex = true;
p.testF = 1.3f;
p.testD = 1.3;
p.ids = new int[] { 1, 2, 3, 4 };
p.ids2 = new List<int>() { 1, 2, 3, 4 };
p.dic = new Dictionary<int, string>() { { 1, "123" }, { 2, "123" } };
p.dic2 = new Dictionary<string, string>() { { "1", "123" }, { "2", "123" } };
p.s1 = new Student(1, "Hong");
p.s2 = new List<Student>() { new Student(2, "Ming"), new Student(3, "Qiang") };
// JsonUtility.ToJson() You can serialize a class object to json character string
string jsonStr = JsonUtility.ToJson(p);
File.WriteAllText(Application.streamingAssetsPath+ "/Person.json", jsonStr);After serialization Json The file stores :
{"name":"Well","age":19,"sex":true,"testF":1.2999999523162842,"testD":1.3,"ids":[1,2,3,4],"ids2":[1,2,3,4]}You can find , Dictionaries 、Student、 private 、 Protection data is not stored
Be careful :
- float There will appear to be some error in serialization , But there is no effect when reading
- Custom classes need to be serialized [System.Serializable], The outermost class does not need to be added
[System.Serializable]
class Student {
public int age;
public string name;
public Student(int age, string name) {
this.age = age;
this.name = name;
}
}then Json The content of is :
{"name":"Well","age":19,"sex":true,"testF":1.2999999523162842,"testD":1.3,"ids":[1,2,3,4],"ids2":[1,2,3,4],"s1":{"age":1,"name":"Hong"},"s2":[{"age":2,"name":"Ming"},{"age":3,"name":"Qiang"}]}- Want to serialize private variables , Need to add features [SerializeField]
[SerializeField] private int privateI = 1;
[SerializeField] protected int protectedI = 2;The result is :
{"name":"Well","age":19,"sex":true,"testF":1.2999999523162842,"testD":1.3,"ids":[1,2,3,4],"ids2":[1,2,3,4],"s1":{"age":1,"name":"Hong"},"s2":[{"age":2,"name":"Ming"},{"age":3,"name":"Qiang"}],"privateI":1,"protectedI":2}- JsonUtility Dictionary is not supported
- JsonUtility Storage null The object will not be null, It is the default data
for example : Make s1=null, that Json What's stored in the file is :"s1":{"age":0,"name":""}
(4)JsonUtlity Deserialization
Deserialization is to read the data on the hard disk into memory , The way is through API:JsonUtility.FromJson( character string )
The deserialization is performed through the member name of the class and json The key names in the file are matched and assigned
Be careful : If Json There is less data in , No error will be reported when reading the class object in memory , For example, deserialize the above content :
jsonStr = File.ReadAllText(Application.persistentDataPath + "/Person.json");
// Method 1 :
Person p2 = JsonUtility.FromJson(jsonStr, typeof(Person)) as Person;
// Method 2 :
Person p3 = JsonUtility.FromJson<Person>(jsonStr);So the results are as follows , You can find that the object of the dictionary class is null Of

(5)JsonUtility matters needing attention
- JsonUtility Unable to read data set directly
For example, one car.json This is what the document says :
[
{"id":1, "speed":6},
{"id":2, "speed":10}
]Then the corresponding object is :
class Car {
public int id;
public int speed;
}It is not possible to deserialize it directly to List<Car> Medium , Must be List<Car> Wrapped in an object , For example, a class has a List<Car> listCar member , Yes Car add [System.Serializable] characteristic , alike , To put json The document is wrapped in braces :
{
"listCar":[
{"id":1, "speed":6}
{"id":2, "speed":10}
]
}- The text encoding format needs to be UTF-8, Otherwise, you cannot load
6、LitJson
(1)LitJson What is it?
Third party Library , be used for Json Serialization and deserialization ,LitJson yes C# To write , Small volume 、 Fast 、 Easy to use , It can be easily embedded in code , Only need to LitJson Copy the code into the project
(2) obtain LitJson
Go to LitJson Official website
Go to... Through the official website Github Get the latest version code
take src/LitJson Copy the code to Unity In Engineering , Start using LItJson
(3) Use LitJson serialize
Method :JsonMapper.ToJson( object )
Be careful :
- relative JsonUtility There is no need to add features
- Cannot serialize private variables
- Dictionary types are supported
- Need to quote LitJson Namespace
- LitJson It can be saved null type
Use the same example as above , But the object above 、 Member's properties removed ( Because these features are aimed at JsonUtility Of ), And then call :
string jsonStr = JsonMapper.ToJson(p);
File.WriteAllText(Application.streamingAssetsPath + "/Person.json", jsonStr);The result is :
{"name":"Well","age":19,"sex":true,"testF":1.3,"testD":1.3,"ids":[1,2,3,4],"ids2":[1,2,3,4],"dic":{"1":"123","2":"123"},"dic2":{"1":"123","2":"123"},"s1":null,"s2":[{"age":2,"name":"Ming"},{"age":3,"name":"Qiang"}]}You can find , Dictionaries can store ( Dictionary keys are strings ), meanwhile null Be able to express , But private 、 Protection variables cannot be stored , If Chinese is stored , The representation method is the same as JsonUtility Are not the same as
(4) Use LitJson deserialize
Method :JsonMapper.ToObject( character string )
jsonStr = File.ReadAllText(Application.streamingAssetsPath + "/Person.json");Method 1 :
// JsonData yes LItJson Class objects provided , The contents can be accessed in the form of key value pairs
JsonData data = JsonMapper.ToObject(jsonStr);
print(data["name"]);
print(data["age"]);Method 2 :
Person p2 = JsonMapper.ToObject<Person>(jsonStr);But in fact, method 2 will report an error
ArgumentException: The value '1' is not of type 'System.Int32' and cannot be used in this generic collection.because json The keys stored in the dictionary in the text are in the form of strings , And Person Class int Mismatch
And then put Person Class dic Dictionary notes , If you continue, there will be another error report :
MissingMethodException: Default constructor not found for type Lesson2+StudentThis is because Student There is no parameterless constructor in the class , After adding a parameterless construct to it, you can deserialize normally
Be careful :
- Class structure requires a parameterless constructor , Otherwise, an error is reported in deserialization
- Although the dictionary supports , But there are problems when keys are used as numeric values , You need to use the string type
(5) matters needing attention
- LitJson Data sets can be read directly
Or to car For example :
jsonStr = File.ReadAllText(Application.streamingAssetsPath + "/car.json");
Car[] arr = JsonMapper.ToObject<Car[]>(jsonStr);
List<Car> arr2 = JsonMapper.ToObject<List<Car>>(jsonStr);This can be directly transformed
If you need to transfer the dictionary directly , Suppose a dictionary data dic.json by :
{
"name": 1,
"name2": 2,
"name3": 3,
"name4": 4
}Be careful !!! If name4 There is a comma at the end of the line , There will be an error in deserialization later
Then directly to Dictionary:
jsonStr = File.ReadAllText(Application.streamingAssetsPath + "/dic.json");
Dictionary<string, int> dic = JsonMapper.ToObject<Dictionary<string, int>>(jsonStr);- The text encoding format needs to be UTF-8, Otherwise, you cannot load
(6)LitJson summary
- LitJson Provided serialization / Deserialization method :JsonMapper.ToJson and ToObject<>
- LitJson Don't add features
- LitJson Private variables are not supported
- LitJson Support dictionary serialization and deserialization
- LitJson Data can be deserialized directly into a data set
- LitJson When deserializing , Custom types require parameterless construction
- Json The document encoding format must be UTF-8
7、JsonUtlity and LitJson contrast
(1) The same thing :
- All for Json Serialization and deserialization of
- Json When the document encoding format is required UTF-8
- Method calls are made through static classes
(2) Difference :
- JsonUtility yes Unity Bring their own ,LitJson It is a third party that needs to reference the namespace
- JsonUtility When using a custom class, you need to add properties ,LitJson Unwanted
- JsonUtility Support private variables ( Add features ),LitJson I won't support it
- JsonUtility Dictionary is not supported ,LitJson Support ( But the key can only be a string )
- JsonUtility Data cannot be deserialized directly into a data association ( Array Dictionary ),LitJson Sure
- JsonUtility No parameter free construction is required for custom classes ,LitJson need
- JsonUtility When storing objects, the default value is No null,LitJson Will exist null
边栏推荐
- WEB上传文件预览
- Multivalued mapping: arraylistmultimap and hashmultimap
- JS click the sun and moon to switch between day and night JS special effect
- PostgreSQL source code learning (21) -- fault recovery ② - transaction log initialization
- If not, use the code generator to generate a set of addition, deletion, modification and query (2)
- iQOO 8实测上手体验:王者归来,从不高调
- The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received
- Pyqt5:slider slider control
- 被“内卷”酸翻的OPPO Reno6
- SSL交互过程
猜你喜欢

单片机通信数据延迟问题排查

Instructor add function_ Enable auto fill_ Instructor modification function

three. JS cool technology background H5 animation

postgresql源码学习(十八)—— MVCC③-创建(获取)快照

TweenMax五彩小球弹跳动画

JS click the sun and moon to switch between day and night JS special effect
![[cloud native] what is micro service? How to build it? Teach you how to build the first micro service (framework)](/img/2c/50c692e090d64ab67f7501beb1d989.png)
[cloud native] what is micro service? How to build it? Teach you how to build the first micro service (framework)

Logical deletion_ Swagger2 framework integration

删除CSDN上传图片的水印

Product milestones in May 2022
随机推荐
词汇表的构建——代码补全快餐教程(3)-分词
摘桃子(双指针)
突破中国品牌创新技术实力,TCL做对了什么?
[cloud native] what is micro service? How to build it? Teach you how to build the first micro service (framework)
B_ QuRT_ User_ Guide(17)
cv. Matchtemplate image model matching opencv
R bioinformatics statistical analysis
正则表达式
一文搞懂单片机驱动8080LCD
Basic use of sonarqube platform
postgresql 函数的参数为自定义类型时传参格式
Lombok use
ARM开发板方案与厂商分析
canvas绘图——如何把图形放置画布中心
Reasons why Chinese comments cannot be written in XML
Artalk | how to build a domestic hyperfusion evolutionary base with minimum investment?
How should Xiaobai start the Amazon self support evaluation?
Start QQ through the program to realize automatic login
Free flying animation of paper plane based on SVG
File file = new file ("test.txt") file path