Cher
Cher

Reputation: 2937

Why is my deserialized object null?

I'm simply trying to use Serialization 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 (debugger):

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

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

Upvotes: 1

Views: 891

Answers (3)

Nate Barbettini
Nate Barbettini

Reputation: 53600

You should define your classes with public getters and setters:

public class MyData
{
    public string Name {get; set;}
}

Then, create an instance of the class and serialize it:

var data = new MyData() { Name = "bob" };

var serialized = JsonConvert.SerializeObject(data);
Console.WriteLine(serialized);

When you deserialize, you can use DeserializeObject<T> to tell JSON.NET which type to deserialize back to:

var deserialized = JsonConvert.DeserializeObject<MyData>(serialized);
Console.WriteLine(deserialized.Name);

Live fiddle: https://dotnetfiddle.net/w4B1IK

Upvotes: 1

Timothy Macharia
Timothy Macharia

Reputation: 2926

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.

Upvotes: 2

Dan Roberts
Dan Roberts

Reputation: 2329

Use the generic de-serialise method:

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

Upvotes: 1

Related Questions