解析Json文件方法1:
1、Json格式:
{"textfamily": [{"name": "tao1","age": 10},{"name": "tao2","age": 20}]}
2、解析Json步骤
(1) 读取Text文件:
TextAsset t = Resources.Load<TextAsset>("json/textJson");
(2)转化为存储对象的List
{
Debug.Log(a.name + "+" + a.age);
(2)转化为存储对象的List
FamilyText s = JsonMapper.ToObject<FamilyText >(t.text);
(3)取出解析Json的数据,在对象属性上:
foreach (textData a in s.textfamily)
{
Debug.Log(a.name + "+" + a.age);
}
FamilyText
类:(List<textData>的变量名必须与Json中的对象名一致)
public class FamilyText
{
public List<textData> textfamily = new List<textData>();
{
public List<textData> textfamily = new List<textData>();
}
textData类:
public class textData
{
public string name { get; set; }
public int age { get; set; }
{
public string name { get; set; }
public int age { get; set; }
}
-----------------------------------------------------------------------------------------------------------
解析Json文件方法2:
1、
Json格式:
{"people1": {"name": "tao1","age": 10},"people2": {"name": "tao2","age": 20}}
2、解析Json步骤
(1) 读取Text文件:
TextAsset t = Resources.Load<TextAsset>("json/textJson");
(2)转化为JsonNode对象:(总对象)
JSONNode data=JSON.Parse(t.text);
(3)取到people1,people2........的对象数组
JSONClass obj=data.AsObject;
(4)取到people1,people2.......对象
JSONClass sub1=obj[0] as JSONClass;
JSONClass sub2=obj[1] as JSONClass;
(5)取到对象中的key值:(如“name”....)
obj.key(0),obj.key(1).........
sub1.AsObject.key(0),sub1.AsObject.key(1)........
sub2.AsObject.key(0),sub2.AsObject.key(1).........
(6)取到对象中的value值:
sub[0].ToString(),sub[1].ToString................
--------------------------------------------------------------------------------------------------------
3、
写入Json的方法
(1)声明一个需要存储的对象:
例如:
textData o =new textData ();
(2)为各属性赋值
o.name=""; .......
(3)转化为JSON
string json=JsonMapper.ToJson(o);