1.JsonUtility
- 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 JsonUtilityDemo : MonoBehaviour
- {
- void Start()
- {
- //创建,解析
- //两种方法:
- //LitJson 和 JsonUtility
-
- //创建
- Person person1 = new Person();
- person1.name = "李逍遥";
- person1.age = 18;
- //转成json字符串
- string jsonStr1 = JsonUtility.ToJson(person1);
-
- Person person2 = new Person();
- person2.name = "王小虎";
- person2.age = 8;
-
- Persons persons = new Persons();
- persons.persons = new Person[] { person1, person2 };
- string jspnStr2 = JsonUtility.ToJson(persons);
- Debug.Log(jspnStr2);
- //{"persons":[{"name":"李逍遥","age":18},{"name":"王小虎","age":8}]}
-
- //解析
- Persons ps = JsonUtility.FromJson<Persons>(jspnStr2);
- foreach (Person p in ps.persons)
- {
- Debug.Log(p.name);
- Debug.Log(p.age);
- }
- }
- }
2.LitJson
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using LitJson;
-
- public class Hero
- {
- public string name;
- public int age;
- }
- public class Heros
- {
- public Hero[] heroes;
- }
-
- public class LitJsonDemo : MonoBehaviour
- {
- void Start()
- {
- //Func1();
- //Func2();
- Func3();
- }
-
- //第一种创建和解析的方法
- void Func1()
- {
- Hero hero1 = new Hero();
- hero1.name = "超人";
- hero1.age = 40;
- Hero hero2 = new Hero();
- hero2.name = "蝙蝠侠";
- hero2.age = 45;
-
- Heros heros = new Heros();
- heros.heroes = new Hero[] { hero1, hero2 };
-
- //创建json
- string jsonStr = JsonMapper.ToJson(heros);
- Debug.Log(jsonStr);
- //{"heroes":[{"name":"\u8D85\u4EBA","age":40},{"name":"\u8759\u8760\u4FA0","age":45}]}
-
- //解析json
- Heros hs = JsonMapper.ToObject<Heros>(jsonStr);
- for (int i = 0; i < hs.heroes.Length; i++)
- {
- Debug.Log(hs.heroes[i].name);
- Debug.Log(hs.heroes[i].age);
- }
- }
-
- //第二种创建json的方法
- void Func2()
- {
- /*JsonData jd = new JsonData();//代表js里面的一个类或者一个数组
- //jd.SetJsonType(JsonType.Array);//说明他是一个js数组 可以不写
- jd["name"] = "超人";
- jd["power"] = 90;
- Debug.Log(jd.ToJson());
- //{"name":"\u8D85\u4EBA","power":90}*/
-
- JsonData herosJD = new JsonData();
- JsonData hero1JD = new JsonData();
- hero1JD["name"] = "超人";
- hero1JD["power"] = 90;
- JsonData hero2JD = new JsonData();
- hero2JD["name"] = "蝙蝠侠";
- hero2JD["power"] = 80;
-
- JsonData heros = new JsonData();
- heros.Add(hero1JD);
- heros.Add(hero2JD);
-
- herosJD["heros"] = heros;
-
- Debug.Log(herosJD.ToJson());
- //{"heros":[{"name":"\u8D85\u4EBA","power":90},{"name":"\u8759\u8760\u4FA0","power":80}]}
- }
-
- //第二种解析json的方法
- void Func3()
- {
- string jsonStr = "{'heros':[{'name':'超人','power':90},{'name':'蝙蝠侠','power':80}]}";
- JsonData herosJD = JsonMapper.ToObject(jsonStr);
- JsonData heros = herosJD["heros"];
- foreach (JsonData heroJD in heros)
- {
- Debug.Log(heroJD["name"].ToString());
- Debug.Log((int)heroJD["power"]);
- }
- }
- }