I'm trying to deserialize a json object into ac# object class. I checked how to read in a json file but I could only find examples for how to do this with a simple json but nothing about how to do it with a multi layer json like this:
{
"user":
{
"inventory":
{
"slot1": "item1",
"slot2": "item2",
}
}
}
invntory is not a simple string or int but another json object. I couldn't even find out how a json object variable type is spelled in c# so that I can save the inventory object itself.
public object inventory;
didn't work.
By Using This Site https://json2csharp.com/ To Convert JSON To C# Class
public class Inventory {
public string slot1 { get; set; }
public string slot2 { get; set; }
}
public class User {
public Inventory inventory { get; set; }
}
// Main Class
public class Root {
public User user { get; set; }
}
Now Convert Your JSON To C# Class Object by Using https://www.nuget.org/packages/Newtonsoft.Json/
// JSON
string Json = "{'user': {'inventory': {'slot1': 'item1','slot2': 'item2'}}}";
// Desterilized Object
var myDeserializedClass = JsonConvert.DeserializeObject<Root>(Json);
right now I'm trying to do it this way:
public List<User> users;
TextAsset jsonFile = Resources.Load<TextAsset>("Data/" + fileName);
User userInJson = JsonUtility.FromJson<User>(jsonFile.text);
users.Add(userInJson);
but for
users.Add(userInJson);
I get a NullReferenceException: Object reference not set to an instance of an object and I'm not sure why.
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.