4

I'm using JsonConvert to serialize and deserialize objects from classes like this:

public class DbBulkRequest
{
    public DbEntity[] Updates { get; set; }
}

public class DbEntity
{
    public string Name { get; set; }
    public object Dto { get; set; }
}

When I deserialize Dto, I get an object of type JObject. At the time of deserialization, I want to create strongly typed objects based on Dto. I can create the objects; however, I don't know of a good way of populating their properties. The best I've found is this cheeseball approach:

MyEntity e = JsonConvert.DeserializeObject<MyEntity>(JsonConvert.SerializeObject(dto));

What would be a more efficient solution?

Edward Brey
  • 40,302
  • 20
  • 199
  • 253
  • 1
    I don't think this is more efficient but at least more readable(I think) `MyEntity e = JObject.FromObject(dto).ToObject();` – L.B Dec 30 '13 at 21:48

1 Answers1

3

Add TypeNameHandling

private readonly JsonSerializerSettings defaultSettings = new JsonSerializerSettings
    {
        Formatting = Formatting.Indented,
        TypeNameHandling = TypeNameHandling.Auto
    };

Here's example

private readonly JsonSerializerSettings defaultSettings = new JsonSerializerSettings
    {
        Formatting = Formatting.Indented,
        TypeNameHandling = TypeNameHandling.Auto
    };

[Fact]
public void Test()
{
    var entity = new DbEntity
        {
            Dto = new TestDto { Value = "dto" },
            Name = "Entity"
        };
    string serializedObject = JsonConvert.SerializeObject(entity, defaultSettings);
    var deserializedObject = JsonConvert.DeserializeObject<DbEntity>(serializedObjest, defaultSettings);
}

public class DbBulkRequest
{
    public DbEntity[] Updates { get; set; }
}

public class DbEntity
{
    public object Dto { get; set; }
    public string Name { get; set; }
}

public class TestDto
{
    public string Value { get; set; }
}
Edward Brey
  • 40,302
  • 20
  • 199
  • 253
GSerjo
  • 4,725
  • 1
  • 36
  • 55