3

I have a Load function in my C# Model, and in that I want to be able to take a JSON string and deserialize it into the current model, for example:

this = JsonConvert.DeserializeObject<Settings>(leJson);

But obviously I can't do that, but I'm struggling on thinking how to do it.

4
  • there can be possibility that your model and Json is different show your class and json sample data Commented Nov 24, 2013 at 9:27
  • Well, the error is in the compiler, not at runtime. The error if i try and set a value to this is Cannot assign to '<this>' because it is read-only. Commented Nov 24, 2013 at 9:30
  • why are you using this , assign it to class reference variable Commented Nov 24, 2013 at 9:33
  • How would I do that from inside the class? Commented Nov 24, 2013 at 9:34

1 Answer 1

3

That's impossible. You cannot write to the this variable from within the instance. You should do that from an outside class. Or have your method return the class instance:

public static Settings GetSettings()
{
    return JsonConvert.DeserializeObject<Settings>(leJson);
}
Sign up to request clarification or add additional context in comments.

7 Comments

So there is no way to load, and apply, settings inside the class?
No, not globally. You will have to do it property by property if you want to do this from inside the class. The easiest would be to simply get a new instance if you have lots of properties.
Ah okay, that's annoying but on well.
@AgentFire, what about them?
@DarinDimitrov DeserializeObjectAsync returns Task, so yuo might want to await for it. Otherwise, Task<Settings> does not simply casts to Settings.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.