问题描述
下面的代码出现以下错误:
I get the following error with the code below:
"非静态字段、方法或属性 'Response.PropName'"
"An object reference is required for the non-static field, method, or property 'Response.PropName'"
代码:
推荐答案
您尝试做的事情是可能的,但不是微不足道的,并且不能仅使用 JSON.NET 的内置属性来完成.您将需要一个自定义属性和一个自定义合同解析器.
What you're trying to do is possible, but not trivial, and can't be done with only the built-in attributes from JSON.NET. You'll need a custom attribute, and a custom contract resolver.
这是我想出的解决方案:
Here's the solution I came up with:
声明这个自定义属性:
将其应用于您的 Data
属性
Apply it to your Data
property
(0是T
在Response
的泛型类型参数中的位置)
(0 is the position of T
in Response<T>
's generic type parameters)
声明以下合约解析器,它将查找 JsonPropertyGenericTypeName
属性并获取类型参数的实际名称:
Declare the following contract resolver, which will look for the JsonPropertyGenericTypeName
attribute and get the actual name of the type argument:
在您的序列化设置中使用此解析器进行序列化:
Serialize with this resolver in your serialization settings:
这将为 Response<Foo>
这篇关于如何获得<T>的名字从泛型类型并将其传递给 JsonProperty()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!