代码一:(LitJson:需要导入LitJson)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LitJson;//添加命名空间 using System.IO;// namespace biji25_20170525_Json { class Program { static void Main(string[] args) { List<Skill> skilllist = new List<Skill>(); if (false)//注释代码功能 { //第一种解析方式 JsonData jsonData = JsonMapper.ToObject(File.ReadAllText("Skill.txt")); foreach (JsonData item in jsonData) { Skill skill = new Skill(); //解析出来的所有数据都是jsondata类型 JsonData id = item["ID"]; JsonData name = item["Name"]; JsonData damage = item["Damage"]; int idValue = int.Parse(id.ToString()); string nameValue = name.ToString(); int damageValue = int.Parse(damage.ToString()); skill.ID = idValue; skill.Name = nameValue; skill.Damage = damageValue; skilllist.Add(skill); } if (skilllist != null) { foreach (var item in skilllist) { Console.WriteLine(item); } } Console.WriteLine(); Console.ReadKey(); //第二种解析方式 (类属性必须与Json串的键保持一致(名字相同)) Skill[] skillArray = JsonMapper.ToObject<Skill[]>(File.ReadAllText("Skill.txt")); foreach (var item in skillArray) { Console.WriteLine(item); } Console.WriteLine(); Console.ReadKey(); //第三种 skilllist = JsonMapper.ToObject<List<Skill>>(File.ReadAllText("Skill.txt")); foreach (var item in skilllist) { Console.WriteLine(item); } Console.WriteLine(); Console.ReadKey(); //—————— Player p = JsonMapper.ToObject<Player>(File.ReadAllText("Player.txt")); foreach (var item in p.Skill) { Console.WriteLine(item); } Console.WriteLine(); Console.ReadKey(); //—————— //json的写入 JsonWriter jw = new JsonWriter(); jw.WriteArrayStart();//json里的中括号 //------【{ jw.WriteObjectStart();//json里的花括号 jw.WritePropertyName("Hello");//书写键的名字 jw.Write("Hi");//书写键的值 jw.WriteObjectEnd(); //--}{第二个 jw.WriteObjectStart();//json里的花括号 jw.WritePropertyName("Hello");//书写键的名字 jw.Write("Hi");//书写键的值 jw.WriteObjectEnd(); //--}{第三个 jw.WriteObjectStart();//json里的花括号 jw.WritePropertyName("Hello");//书写键的名字 jw.Write("Hi");//书写键的值 jw.WriteObjectEnd(); //------}】 jw.WriteArrayEnd(); string json = jw.ToString();//获取写好的json串 Console.WriteLine(json); Console.WriteLine(); Console.ReadKey(); //—————— } //———————————————————————— JsonData data = JsonMapper.ToObject(File.ReadAllText("Skill.txt")); foreach (JsonData item in data ) { item["ID"] = 5; } JsonWriter jw1 = new JsonWriter(); data.ToJson(jw1); string json1 = jw1.ToString(); Console.WriteLine(json1); File.WriteAllText("Skill1.txt", json1); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace biji25_20170525_Json { class Player { public string Name; public int Level; public int Money; public List<Skill> Skill; public override string ToString() { return string.Format("Name:{0}", "Level:{1}", "Money:{2}", Name, Level, Money); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace biji25_20170525_Json { class Skill { public int ID; public string Name; public int Damage; public override string ToString() { return string.Format("ID:{0} Name:{1} Damage:{2}", ID, Name, Damage); } } }
代码二:(不需要导入)
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Jsons : MonoBehaviour { void Start() { TestClass tc = new TestClass(); tc.testName = "ABC"; tc.testPrice = 100; tc.testFloat = 10.1f; tc.testIntArray = new int[] { 1, 2, 5 }; tc.testStringArray = new string[] { "星期一", "星期二", "星期三" }; tc.testItemInfo = new ItemInfo() { ID = "1001", itemName = "屠龙宝刀" }; ItemInfo itemA = new ItemInfo() { ID = "1002", itemName = "屠龙刀" }; ItemInfo itemB = new ItemInfo() { ID = "1003", itemName = "刀" }; tc.testItemInfoArray = new ItemInfo[] { itemA, itemB }; tc.testDic.Add("2005", "yitianjian"); tc.testDic.Add("1008", "tulongdao"); tc.testItemDic.Add("AA", itemA); tc.testItemDic.Add("BB", itemB); string testJson = JsonUtility.ToJson(tc); Debug.Log(testJson); } } public class ItemInfo { public string ID; public string itemName; //public string des;//描述 //public int price; //public string type; //public string wearType;//穿戴类型 //public int lv;//穿戴等级 //public string quality;//品质 //public int atk; //public int def; //public int curHp; //public int maxHp; //public int curMp; //public int maxMp; } public class TestClass { public string testName; public int testPrice; public float testFloat; public int[] testIntArray; public string[] testStringArray; public List<string> testStrList = new List<string>(); public ItemInfo testItemInfo; public ItemInfo[] testItemInfoArray; public Dictionary<string, string> testDic = new Dictionary<string, string>(); public Dictionary<string, ItemInfo> testItemDic = new Dictionary<string, ItemInfo>(); }
代码三:(NewTonJson:需要导入NewTonJson)
using UnityEngine; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; //using System.Linq; /// <summary> /// 管理所有物品 /// </summary> public class ItemMgr : MonoBehaviour { public static ItemMgr instance; public TextAsset m_TextAsset; private AllItemInfo infos; private Dictionary<string, ItemInfo> itemDic = new Dictionary<string, ItemInfo>();//存放药品 void Awake() { instance = this; infos = JsonConvert.DeserializeObject<AllItemInfo>(m_TextAsset.text); foreach (ItemInfo item in infos.itemList) { itemDic.Add(item.IDs, item); } } } /// <summary> /// 物品信息 /// </summary> public class ItemInfo { public string IDs; public string Name; /// <summary> /// 描述 /// </summary> public string des; public int price; public string type; public string wearType;//穿戴类型 public int lv;//穿戴等级 public string quality;//品质 public int atk; public int def; public int curHp; public int maxHp; public int curMp; public int maxMp; } /// <summary> /// 物品信息列表,存储所有物品信息 /// </summary> public class AllItemInfo { public List<ItemInfo> itemList = new List<ItemInfo>(); }
文本:(Json格式的文本)
{ "itemList": [ { "ID": "1001", "Name": "生命药水", "Des": "回复一定量的生命", "Price": "100", "Type": "药品", "WearType": "null", "WearLv": "0", "Quality": "普通", "Atk": "0", "Def": "0", "CurHp": "100", "MaxHp": "0", "CurMp": "0", "MaxMp": "0" }, { "ID": "1002", "Name": "魔法药水", "Des": "回复一定量的魔法", "Price": "100", "Type": "药品", "WearType": "null", "WearLv": "0", "Quality": "普通", "Atk": "0", "Def": "0", "CurHp": "0", "MaxHp": "0", "CurMp": "100", "MaxMp": "0" }, { "ID": "2001", "Name": "屠龙刀", "Des": "武林至尊宝刀屠龙号令天下谁敢不从", "Price": "2000", "Type": "装备", "WearType": "武器", "WearLv": "1", "Quality": "普通", "Atk": "200", "Def": "0", "CurHp": "0", "MaxHp": "0", "CurMp": "0", "MaxMp": "0" } ] }
JsonNetSample:
using System; using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public class JsonNetSample : MonoBehaviour { public Text Output; void Start() { Output.text = "Start!\n\n"; TestJson(); SerailizeJson(); DeserializeJson(); LinqToJson(); JsonPath(); WriteLine("\nDone!"); } void WriteLine(string msg) { Output.text = Output.text + msg + "\n"; } public class Product { public string Name; public DateTime ExpiryDate = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc); public decimal Price; public string[] Sizes; public override bool Equals(object obj) { if (obj is Product) { Product p = (Product)obj; return (p.Name == Name && p.ExpiryDate == ExpiryDate && p.Price == Price); } return base.Equals(obj); } public override int GetHashCode() { return (Name ?? string.Empty).GetHashCode(); } } [System.Serializable] public class CharacterListItem { public int Id { get; set; } public string Name { get; set; } public int Level { get; set; } public string Class { get; set; } public string Sex { get; set; } } void TestJson() { WriteLine("* TestJson"); var json = "{\"Id\":51, \"Name\":\"padre\", \"Level\":0, \"Class\":\"Vampire\", \"Sex\":\"F\"}"; var c = JsonConvert.DeserializeObject<CharacterListItem>(json); WriteLine(c.Id + " " + c.Name); } void SerailizeJson() { WriteLine("* SerailizeJson"); Product product = new Product(); product.Name = "Apple"; product.ExpiryDate = new DateTime(2008, 12, 28); product.Sizes = new string[] { "Small" }; string json = JsonConvert.SerializeObject(product); WriteLine(json); } public class Movie { public string Name { get; set; } public string Description { get; set; } public string Classification { get; set; } public string Studio { get; set; } public DateTime? ReleaseDate { get; set; } public List<string> ReleaseCountries { get; set; } } void DeserializeJson() { WriteLine("* DeserializeJson"); string json = @"{ ‘Name‘: ‘Bad Boys‘, ‘ReleaseDate‘: ‘1995-4-7T00:00:00‘, ‘Genres‘: [ ‘Action‘, ‘Comedy‘ ] }"; Movie m = JsonConvert.DeserializeObject<Movie>(json); string name = m.Name; WriteLine(name); } void LinqToJson() { WriteLine("* LinqToJson"); JArray array = new JArray(); array.Add("Manual text"); array.Add(new DateTime(2000, 5, 23)); JObject o = new JObject(); o["MyArray"] = array; string json = o.ToString(); WriteLine(json); } private void JsonPath() { WriteLine("* JsonPath"); var o = JObject.Parse(@"{ ‘Stores‘: [ ‘Lambton Quay‘, ‘Willis Street‘ ], ‘Manufacturers‘: [ { ‘Name‘: ‘Acme Co‘, ‘Products‘: [ { ‘Name‘: ‘Anvil‘, ‘Price‘: 50 } ] }, { ‘Name‘: ‘Contoso‘, ‘Products‘: [ { ‘Name‘: ‘Elbow Grease‘, ‘Price‘: 99.95 }, { ‘Name‘: ‘Headlight Fluid‘, ‘Price‘: 4 } ] } ] }"); JToken acme = o.SelectToken("$.Manufacturers[?(@.Name == ‘Acme Co‘)]"); WriteLine(acme.ToString()); IEnumerable<JToken> pricyProducts = o.SelectTokens("$..Products[?(@.Price >= 50)].Name"); foreach (var item in pricyProducts) { WriteLine(item.ToString()); } } }