从JSON有效负载读取动态属性的值

从JSON有效负载读取动态属性的值

本文介绍了从JSON有效负载读取动态属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的模型用作请求有效载荷

I have a simple model that I used as a request payload

public class CommandRequest
{
    public CommandType Type { get; set; }
    public dynamic Attributes { get; set; }
}

在控制器操作中,我需要从动态的 Attributes

In controller action I need to read some property from dynamic Attributes

public async Task<IActionResult> Commands([FromBody] CommandRequest requestBody)
{
    string name = requestBody.Attributes.Name;
    ...
}

收到以下异常:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Text.Json.JsonElement' does not contain a definition for 'Name'

我如何阅读该财产?

推荐答案

简单地将某些内容声明为 dynamic 并不能保证所产生的具体对象实现 IDynamicMetaObjectProvider 并允许对属性进行运行时定义.相反, dynamic 仅表示已关闭所有编译时检查的 object ,因此对其的所有方法和成员引用都将在运行时解析.参见:

Simply declaring something as dynamic doesn't guarantee that the resulting concrete object implements IDynamicMetaObjectProvider and allows for runtime definition of properties. Rather, dynamic simply means an object to which all compile-time checking has been turned off, and so all method and member references to it will be resolved in runtime. See:

现在,当使用Json.NET将JSON对象反序列化为声明为 dynamic 的成员时,Newtonsoft将选择 JObject 作为要反序列化的具体类型.作为其基本类型, JToken 实现 IDynamicMetaObjectProvider ,您可以执行 requestBody.Attributes.Name 之类的操作,.Net运行时会将属性解析转发到 JObject ,后者将查找属性在其属性列表中.但是,这不是自动发生的,Newtonsoft必须增强 JToken 以使动态属性访问成为可能.

Now, when you deserialize a JSON object to a member declared as dynamic with Json.NET, Newtonsoft will chose JObject as the concrete type to which to deserialize. As its base type JToken implements IDynamicMetaObjectProvider you can do things like requestBody.Attributes.Name and the .Net runtime will forward the property resolution to the JObject which will look the property up inside its list of properties. However, this doesn't happen automatically, Newtonsoft had to enhance JToken to make dynamic property access possible.

System.Text.Json 不具有将自由格式JSON反序列化为实现 IDynamicMetaObjectProvider 的某些自定义类型的内置支持,因此您需要使用返回的实际类型的编译时方法,即. JsonElement ,以访问其中包含的JSON数据:

System.Text.Json, however, does not have built-in support for deserializing free-form JSON to some custom type implementing IDynamicMetaObjectProvider, so you will need to use the compile-time methods of the actual type returned, viz. JsonElement, to access the JSON data contained therein:

var name = requestBody.Attributes.GetProperty("Name").ToString();

或者,为了清楚起见,可以将其强制转换为

Or, you could cast it for clarity:

var name = ((JsonElement)requestBody.Attributes).GetProperty("Name").ToString();

演示小提琴此处.

这篇关于从JSON有效负载读取动态属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 02:01