Unity3D_(数据)JsonUtility创建和解析Json
Json 百度百科:传送门
LitJson创建和解析Json 传送门
Json数据解析在Unity3d中的应用 传送门
一、使用JsonUnity创建Json
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; [Serializable] public class Person { public string name; public int age; } public class JSON_Gary : MonoBehaviour { // Use this for initialization void Start () { //Json操作 两种方式 ListJson JsonUtility //使用代码的方式创建一个json //{'name':'Gary','age':20} Person p1 = new Person(); p1.name = "Gary"; p1.age = 20; //转成json字符串 string jsonStr = JsonUtility.ToJson(p1); Debug.Log(jsonStr); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; [Serializable] public class Person { public string name; public int age; } [Serializable] public class Persons { public Person[] persons; } public class JSON_Gary : MonoBehaviour { // Use this for initialization void Start () { //Json操作 两种方式 ListJson JsonUtility //使用代码的方式创建一个json //{'name':'Gary','age':20} Person p1 = new Person(); p1.name = "Gary"; p1.age = 20; //转成json字符串 string jsonStr = JsonUtility.ToJson(p1); //Debug.Log(jsonStr); //{'persons':[{'name':'Gary','age':20},{'name':'Gary2','age':25}]} Person p2 = new Person(); p2.name = "Gary2"; p2.age = 25; Person[] ps = new Person[] { p1, p2 }; Persons persons = new Persons(); persons.persons = ps; jsonStr = JsonUtility.ToJson(persons); Debug.Log(jsonStr); } }
二、使用JsonUtility解析Json
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; [Serializable] public class Person { public string name; public int age; } [Serializable] public class Persons { public Person[] persons; } public class JSON_Gary : MonoBehaviour { // Use this for initialization void Start () { //Json操作 两种方式 ListJson JsonUtility //使用代码的方式创建一个json //{'name':'Gary','age':20} Person p1 = new Person(); p1.name = "Gary"; p1.age = 20; //转成json字符串 string jsonStr = JsonUtility.ToJson(p1); //Debug.Log(jsonStr); //{'persons':[{'name':'Gary','age':20},{'name':'Gary2','age':25}]} Person p2 = new Person(); p2.name = "Gary2"; p2.age = 25; Person[] ps = new Person[] { p1, p2 }; Persons persons = new Persons(); persons.persons = ps; jsonStr = JsonUtility.ToJson(persons); //jsonStr ={ 'persons':[{'name':'Gary','age':20},{'name':'Gary2','age':25}]} //Debug.Log(jsonStr); //解析Json Persons newPersons = JsonUtility.FromJson<Persons>(jsonStr); Debug.Log(newPersons.persons[0].name); } }
https://www.cnblogs.com/qiaogaojian/p/6532665.html
(如需转载学习,请标明出处)