Cher Cher - 1 year ago 96
C# Question

Why is my deserialized object null?

I'm simply trying to use

properties to temporary store datas in a string. I tested many method and those functions are the ones I could use (since in my real classes I have ObjectId, a lot of serialization classes don't work).

However, even with a simple test it doesn't work, my deserialization is null:

public class MyClass
public string test = "bob";

static public void function()
MyClass test = new MyClass();

string data = Newtonsoft.Json.JsonConvert.SerializeObject(test);
object testb = Newtonsoft.Json.JsonConvert.DeserializeObject(data);
MyClass testa = Newtonsoft.Json.JsonConvert.DeserializeObject(data) as MyClass;

Results are (

datab : { "test": "bob"}
testa is null.

Why? How can I convert an object like testb with keys and value to my correct type?

Answer Source

Problem is the way you are type casting.

Try out this one and it should work just fine

MyClass testa = Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass>(data);

That shall be all.