创建Json
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestJson : MonoBehaviour
{
void Start ()
{
CreateJson();
}
public void CreateJson()
{
Person person = new Person() { theName = "张三", theAge = 15 };
string jsonStr = JsonUtility.ToJson(person);
Debug.Log(jsonStr);
}
}
public class Person
{
public string theName;
public int theAge;
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestJson : MonoBehaviour
{
void Start ()
{
CreateJson();
}
public void CreateJson()
{
Person person1 = new Person() { theName = "张三", theAge = 15 };
Person person2 = new Person() { theName = "李四", theAge = 25 };
Persons persons = new Persons { persons=new Person[] { person1, person2 } };
string jsonStr = JsonUtility.ToJson(persons);
Debug.Log(jsonStr);
}
}
[Serializable]
public class Person
{
public string theName;
public int theAge;
}
[Serializable]
public class Persons
{
public Person[] persons;
}
解析Json
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestJson : MonoBehaviour
{
void Start ()
{
ReadJson(CreateJson());
}
public string CreateJson()
{
Person person1 = new Person() { theName = "张三", theAge = 15 };
Person person2 = new Person() { theName = "李四", theAge = 25 };
Persons persons = new Persons { persons=new Person[] { person1, person2 } };
string jsonStr = JsonUtility.ToJson(persons);
return jsonStr;
}
public void ReadJson(string jsonStr)
{
Persons person = JsonUtility.FromJson<Persons>(jsonStr);
foreach (Person item in person.persons)
{
Debug.Log(item.theName);
Debug.Log(item.theAge);
}
}
}
[Serializable]
public class Person
{
public string theName;
public int theAge;
}
[Serializable]
public class Persons
{
public Person[] persons;
}
使用LitJson
在Project视图创建文件夹“Plugins” 。
将LitJson文件放入文件夹。
创建脚本并导入命名空间:“using LitJson;”
具体实现参看:
https://blog.csdn.net/NCZ9_/article/details/85235214