R
R
Rag'n' Code Man2020-05-06 03:19:03
JSON
Rag'n' Code Man, 2020-05-06 03:19:03

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


And then using Unity JsonUtility do this:
object settingsText = JsonUtility.FromJson<object>("./text.json");


Can I then do this text.SetText(settingsText.settings.volume.ru);:

Can C# generate objects with the given properties on its own, or is this burden solely on the developer, and it will be up to me to create the SettingsText class with these fields?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
2
2CHEVSKII, 2020-05-06
@2chevskii

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.

D
Daniil Demidko, 2020-05-06
@Chronicler

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 question

Ask a Question

731 491 924 answers to any question