使用 JSON.NET 将属性反序列化为 ExpandoObject

编程入门 行业动态 更新时间:2024-10-28 18:28:15
本文介绍了使用 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.

更多推荐

使用 JSON.NET 将属性反序列化为 ExpandoObject

本文发布于:2023-11-14 21:28:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588542.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   属性   JSON   NET   ExpandoObject

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!