Answer the question
In order to leave comments, you need to log in
Is it possible in C# to cast JSON to an object without first creating it?
Good evening!
I'm still making my clicker and I got the idea to translate it into English as I'm going to post it on itch.io .
But since the computer is quite far from me, and I can only check it myself in a week and a half, I am writing here.
We all know that when we deserialize a class, we again substitute some values into its fields, that is, if we serialized variable B for class A, then during deserialization, property B of an object of class A will store this value.
So, let's say I want to create a JSON object of this kind, where I will store the text for the settings window (for example):
{
"settings": {
"volume": {
"ru": "Громкость звука",
"en": "Sound Volume"
},
"removeads": {
"ru": "Убрать рекламу",
"en": "Remove Ads"
}
}
}
object settingsText = JsonUtility.FromJson<object>("./text.json");
text.SetText(settingsText.settings.volume.ru);
: Answer the question
In order to leave comments, you need to log in
No, you can't, because object does not contain such fields. Despite the fact that the resulting object actually contains these fields, when packing, such a construction will give a compilation error. There are two ways out - to use Json.Net, which deserializes everything into its jobject, which, in fact, are dictionaries, or use the DLR, but, as for me, it's better to hang yourself than to use such a slow theme.
JSON is just text. You can write anything in it.
If all the required fields are available, then you can deserialize later.
The answer is yes.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question