Deserialize a property as an ExpandoObject using JSON.NET

前端 未结 1 1989
孤城傲影
孤城傲影 2021-01-04 05:06

For example, there\'s an object like the next one:

public class Container
{
   public object Data { get; set; }
}

And it\'s used this way:<

相关标签:
1条回答
  • 2021-01-04 05:58

    Try this:

    Container container = new Container
    {
        Data = new Dictionary<string, object> { { "Text", "Hello world" } }
    };
    
    string jsonText = JsonConvert.SerializeObject(container);
    
    var obj = JsonConvert.DeserializeObject<ExpandoObject>(jsonText, new ExpandoObjectConverter());
    

    I found that doing this got me an ExpandoObject from the call to DeserializeObject. I think the issue with the code you have provided is that while you are supplying an ExpandoObjectConverter, you are asking Json.Net to deserialize a Container, so I would imagine that the ExpandoObjectConverter is not being used.

    Edit:

    If I decorate the Data property with [JsonConverter(typeof(ExpandoObjectConverter))] and use the code:

    var obj = JsonConvert.DeserializeObject<Container>(jsonText);
    

    Then the Data property is deserialized to an ExpandoObject, while obj is a Container.

    0 讨论(0)
提交回复
热议问题