Answer the question
In order to leave comments, you need to log in
How to deserialize an array of named objects in an object using the Unity JsonUtility?
Have a good time, benevolent! Brother, help me out, you need to deserialize JSON into C # Object using standard Unity tools, below I will give an example of what I want. You just need to suggest how to competently implement a class for serializing / deserializing a JSON string.
{
"cars": [
{"cars_bigs": [{"force": 500, "weight": 1000}, {"force": 1000, "weight": 4000}]},
{"cars_smaller": [{"force": 100, "weight": 800}, {"force": 300, "weight": 400}]}
]
}
[Serializable]
public class CarsResult {
public CarItem[] cars;
}
[Serializable]
public class CarItem {
public string CarType;
public Car[] CarObjects;
}
[Serializable]
class Car {
public int force;
public int weight
}
Answer the question
In order to leave comments, you need to log in
1. Your json looks like this:
- cars
- cars_bigs
- force: 500
weight: 1000
- force: 1000
weight: 4000
- cars_smaller
# и так далее
class CarsResult {
public CarItem[] Cars { get; set; }
}
class CarItem {
// К сожалению, нельзя на уровне системы типов выразить "Объект, у которого есть либо поле А либо поле Б"
// Так что придётся указать оба поля
// И нельзя это разрулить на уровне настроек сериализатора, если не придумывать кастомный сериализатор (не знаю, можно ли кастомизировать юнитивский)
public Car[] BigCars { get; set; }
public Car[] SmallCars { get; set; }
}
class Car {
public int Force { get; set; }
public int Weight { get; set; }
}
The standard json is either semi-working, or I don’t understand something, I also had problems with it and the output was the newtonsoft library, it seems that the unit immediately has it, try it, everything worked with it
1) Don't use Unity's standard JSON - it's terrible, it doesn't work with nesting levels greater than 1.
2) Newtonsoft is much better, the Unity team themselves included it in their packages.
3) To read a class in JSON, you need to create it with the [Serializable] attribute. Also note that not all base classes/structs in Unity can be serialized. For example, there may be problems with Vector3, in some places you may need to write your own class for this.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question