简体   繁体   中英

Newtosoft Json library deserialization RuntimeBinderException in Unity

I'm importing a C# project to Unity. Newtonsoft json library works well in a C# project (as a Nugget package), but it throws an exception in Unity (as an asset store package). I'm using newest packages and the following syntax:

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

Newtonsoft library in Unity throws an exception (on line 2):

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

My data format (simplified):

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

What would be a good way to bypass this issue?

Create Model And then DeserializeObject and access all the values

I am Reading Same your json From D://readjson.txt in my example

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; }
    }
}

Another Approach maybe you need this:-

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);
            }

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM