Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing object[] that contains primitive types and one class type

I have an object array that contains strings and longs and this class:

public class SimpleMailAddress
{
    public string Address { get; set; }
    public string Name { get; set; }

    public static implicit operator MailAddress(SimpleMailAddress m)
    {
        return new MailAddress(m.Address, m.Name);
    }
}

However, when deserializing the JSON array with Json.Net, I get an anonymous type that contains Address and Name instead of a SimpleMailAddress object.

I don't want to create a strongly-typed object to deserialize into because it will not be reused and I'd have to create a lot of objects for it. Is there a way to do this with Json.Net or any other library?

This is how I'm serializing/deserializing:

var json = JsonConvert.SerializeObject(myObject);
var myObject = JsonConvert.DeserializeObject<MailMessageRequest>(json);

And MailMessageRequest:

public class MailMessageRequest
{
    public string Mailer { get; set; }
    public string Method { get; set; }
    public object[] Args { get; set; }
}
like image 339
Caleb Jares Avatar asked May 25 '13 04:05

Caleb Jares


1 Answers

Json does not contain any inherit knowledge about your SimpleMailAddress class. So when you are telling it to deserialize, the fact that your Args property is of type Object, the deserializer is doing the best it can (by creating an anonymous type). It just sees data, it has no knowledge that you want a SimpleMailAddress object.

Json.net has a JObject class. Try using that instead of Object for your Args parameter if the actual contents of Args may change type.

Then, as needed, you can read the data from the JObject object.

If you don't care about the actual contents of Args, then leave it as Object and ignore it.

Edit: JSon.Net can embed type information during serialization that can be used during deserialization.

Leave your Args parameter as an Object. Then use the TypeNameHandling option of All during both serialization and deserialization.

var json = JsonConvert.SerializeObject(myObject, Formatting.None, 
    new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
var myObject = JsonConvert.DeserializeObject<MailMessageRequest>(json, 
    new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });

You should end up with your Args object as your desired SimpleMailAddress object.

like image 122
Matt Houser Avatar answered Nov 17 '22 08:11

Matt Houser