Unity自带的json解析工具JsonUtility遇到的坑
2017-06-16 本文已影响0人
HMY轩园
json 字符串可以是json或txt文本文件,但保存必须是
如果是Utf-8有签名,简析就一直报错(本人这儿遇到的第一个坑)
错误:ArgumentException: JSON parse error: Invalid value.
另外一个坑就是json字符串里的名字与C#里需要保持一致:
json 字符串:
{
"datainfo": [
{
"name": "text1",
"uitxture": "text1.jpg",
"mode": "text1+1",
"assetname": "text111111",
"type": 0,
"Scalenfo": {
"x": 1.5,
"y": 0.5,
"z": 0.5
}
},
{
"name": "text2",
"uitxture": "text2.jpg",
"mode": "text2+1",
"assetname": "text222222",
"type": 1,
"Scalenfo": {
"x": 0.5,
"y": 0.5,
"z": 0.5
}
}
]
}
C#解析json类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;using System;
using UnityEditor;
[Serializable]
public class jsoninfo {
public data[] datainfo;}
[Serializable]
public class data{
public string name;
public string uitxture;
public string mode;
public string assetname;
public int type;
public Vector3 Scalenfo;
}
public class jsonJiexi : MonoBehaviour {
// Use this for initialization
void Start () {
StartCoroutine(getTxt());
}
IEnumerator getTxt() {
WWW www = new WWW(@"file://"+Application.dataPath+@"/json.txt");
yield return www;
if (www.error!=null)
{ Debug.Log(www.error);
yield return null;
}
Debug.Log(www.text);
string json = www.text.ToString(); Debug.Log(json); jsoninfo d = JsonUtility.FromJson(json);
Debug.Log(d.datainfo[0].name);
Debug.Log(d.datainfo[1].name);
Debug.Log(d.datainfo[1].Scalenfo);
JsonUtility.FromJsonOverwrite(json, d);
}
}
Paste_Image.png