【发布时间】:2017-06-08 10:52:42
【问题描述】:
我想动态更改 json 属性名并序列化对象。
这是我的两个不同实体的 json
为客户
{
"userName": "66666",
"password": "test1234",
"customersList": [
{
"address": "Test Stree2",
"customerNumber": "US01-000281",
"city": ""
}
]
}
联系方式
{
"userName": "66666",
"password": "test1234",
"contactList": [
{
"address": "Test stree1",
"contactNumber": "US01-000281",
"city": ""
}
]
}
持有这些数据的模型如下
public class URequest<T>
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string userName { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string password { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public IList<T> requestList { get; set; }
}
在上面的代码requestList 中可能包含contacts 或customer 的列表,但是在发送时我想将requestList json 属性名称更改为相应的实体名称,即对于customer,它将是customerList 和对于contact,序列化后为contactList。
【问题讨论】:
-
一个自定义解析器可以在这里为您提供帮助,stackoverflow.com/questions/37917164/…
-
您的示例表明,除了标记标识符 (customer-/contactNumber) 之外,customer 和 contact 实际上是相同的。您是否考虑过使用通用实体并仅添加类型标识符?它允许您添加更多类型(“lead”、“superuser”等),而无需更改所有编码。
-
我也有其他类成员,只是为了简化示例,我在两个模型中都考虑了很少的类成员
-
理论上你可以使用
JsonConverter类来做到这一点,虽然我更喜欢@Filburt 的建议:) -
是的,我们可以使用
JsonConveter,但这就是问题所在:)