问题描述
例如,有像下一个对象:
For example, there's an object like the next one:
public class Container
{
public object Data { get; set; }
}
和它的使用是这样的:
Container container = new Container
{
Data = new Dictionary<string, object> { { "Text", "Hello world" } }
};
如果我反序列化从序列上面的实例中,获得的数据JSON字符串
属性,即使我提供 ExpandoObjectConverter
,这不是反序列化作为一个 ExpandoObject
:
If I deserialize a JSON string obtained from serializing the above instance, the Data
property, even if I provide the ExpandoObjectConverter
, it's not deserialized as an ExpandoObject
:
Container container = JsonConvert.Deserialize<Container>(jsonText, new ExpandoObjectConverter());
如何反序列化与匿名对象指定一个类属性,或者至少不具体类型为 ExpandoObject
How can I deserialize a class property assigned with an anonymous object, or at least, not concrete type as an ExpandoObject
?
的有人回答,我可以只使用动态对象。这不会为我工作。我知道我可以走这条路,而是因为我需要一个ExpandoObject不是这种情况。
谢谢的
的其他一些用户回答我可以反序列化一个JSON字符串转换成 ExpandoObject
。这不是这个问题的目的。我需要反序列化具有动态性的具体类型。在JSON字符串该属性可能是一个关联数组的
Some other user answered I could deserialize a JSON string into an ExpandoObject
. This isn't the goal of this question. I need to deserialize a concrete type having a dynamic property. In the JSON string this property could be an associative array.
推荐答案
试试这个:
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());
我发现,这样做让我的 ExpandoObject
从调用 DeserializeObject
。我想与您所提供的代码的问题是,当你在提供一个 ExpandoObjectConverter
,你问 Json.Net
反序列化集装箱
,所以我会想象, 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.
编辑:
如果我装点数据
财产 [JsonConverter(typeof运算(ExpandoObjectConverter))]
,并使用代码:
If I decorate the Data
property with [JsonConverter(typeof(ExpandoObjectConverter))]
and use the code:
var obj = JsonConvert.DeserializeObject<Container>(jsonText);
然后数据
属性被反序列化到 ExpandoObject
,而 OBJ
是集装箱
。
Then the Data
property is deserialized to an ExpandoObject
, while obj
is a Container
.
这篇关于反序列化属性作为使用JSON.NET的ExpandoObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!