使用 JSON.NET 将属性反序列化为 ExpandoObject
例如,有一个类似于下一个的对象:
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 字符串,Data
属性,即使我提供了 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());
我发现这样做可以从对 DeserializeObject
的调用中获得一个 ExpandoObject
.我认为您提供的代码的问题在于,当您提供 ExpandoObjectConverter
时,您要求 Json.Net
反序列化 Container
,所以我认为 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))]
装饰 Data
属性并使用代码:
If I decorate the Data
property with [JsonConverter(typeof(ExpandoObjectConverter))]
and use the code:
var obj = JsonConvert.DeserializeObject<Container>(jsonText);
然后将 Data
属性反序列化为一个 ExpandoObject
,而 obj
是一个 Container
.
Then the Data
property is deserialized to an ExpandoObject
, while obj
is a Container
.