Unity中的Newtosoft Json库反序列化RuntimeBinderException

时间:2018-07-06 19:08:34

标签: c# unity3d json.net

我正在将C#项目导入Unity。 Newtonsoft json库在C#项目(作为Nugget程序包)中运行良好,但在Unity(作为资产存储程序包)中引发了异常。我正在使用最新的软件包和以下语法:

dynamic myObj = JsonConvert.DeserializeObject(jsonString)
dynamic myObj2 = myObj.myObj2 ;

Unity中的Newtonsoft库引发异常(第2行):

RuntimeBinderException: 'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'myObj2 '

我的数据格式(简体):

{
"myObj2": [
    {
        "name": "name1",
        "parameters": [
            {
                "paramName" : "parameter1",
                "type": "Bool",
                "value": "false"
            },
            {
                "paramName" : "parameter2",
                "type": "GameObject",
                "value": "someGameObjectName"
            }               
            ]
    }
]
}

什么是绕过此问题的好方法?

1 个答案:

答案 0 :(得分:0)

创建模型,然后创建DeserializeObject并访问所有值

在我的示例中,我正在从D://readjson.txt读取相同的json

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string data = File.ReadAllText("D://readjson.txt");
            var datavales = JsonConvert.DeserializeObject<RootObject>(data);

            foreach(var vales in datavales.myObj2)
            {
                //access values from here
                Console.WriteLine(vales.name);
            }
        }
    }
    public class Parameter
    {
        public string paramName { get; set; }
        public string type { get; set; }
        public string value { get; set; }
    }

    public class MyObj2
    {
        public string name { get; set; }
        public List<Parameter> parameters { get; set; }
    }

    public class RootObject
    {
        public List<MyObj2> myObj2 { get; set; }
    }
}

另一种方法,也许您需要:-

static void Main(string[] args)
        {
            string data = File.ReadAllText("D://readjson.txt");
            dynamic datavales = JsonConvert.DeserializeObject(data);

            dynamic keydata = datavales.myObj2;
            foreach(dynamic obj2values in keydata)
            {
               //obj2values contain all the values access it using obj2values object
               Console.WriteLine( obj2values.name);
            }

        }