美文网首页
Unity自带的json解析工具JsonUtility遇到的坑

Unity自带的json解析工具JsonUtility遇到的坑

作者: HMY轩园 | 来源:发表于2017-06-16 17:16 被阅读0次

    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

    相关文章

      网友评论

          本文标题:Unity自带的json解析工具JsonUtility遇到的坑

          本文链接:https://www.haomeiwen.com/subject/wcemqxtx.html