的WebAPI - 反序列化和序列化替代属性名称 [英] WebApi - Deserializing and serializing alternate property names
问题描述
我试图找出如何我可以指定ASP.NET的WebAPI备用属性名称 - 并且它反序列化+系列化工作,并为JSON + XML。我只发现了部分解决方案为止。
I'm trying to figure out how I can specify alternate property names with ASP.NET WebApi - and have it work for deserialization + serialization, and for JSON + XML. I've only uncovered partial solutions so far.
我要公开的属性名称与下划线小写,(例如的缘故)有不同的内部名称:
I want to expose the property names as lower case with underscores, and (for example's sake) have different internal names:
的外部:的
- 字段一
- 现场两个
的内部:的
- ItemOne
- ItemTwo
有关测试,这里只是中转它收到一个POST控制器动作:
For testing, here's a POST controller action that just relays what it receives:
// POST api/values
public TestSerialization Post([FromBody]TestSerialization value)
{
return value;
}
和测试实体:
public class TestSerialization
{
[DataMember(Name = "field_one")] // Doesn't appear to change anything
public string ItemOne { get; set; }
[JsonProperty(PropertyName = "field_two")] // Only works for serialization in JSON mode
public string ItemTwo { get; set; }
}
到目前为止,我发现:
So far, I've found:
- [数据成员(名称为×)],但在两个方向上的序列没有影响
- 使用JSON当[JsonProperty(名称=X)适用于序列化(返回值)。 (这是一个JSON.NET属性,默认的序列化)。
有关的测试数据,我提交的4个属性,看看哪些价值被反序列化,什么属性名是反序列化
For test data, I submit 4 properties, to see which value gets deserialized, and what the property name is on deserialization
- ItemOne =值A
- ItemTwo =值B
- 字段一=正确1
- 字段二=正确2
我怎样才能做到这一点?
How can I achieve this?
推荐答案
你的一些研究结果/结论是不正确的......你可以尝试以下代替:
Some of your findings/conclusions are incorrect...you can try the following instead:
这应该适用的两个的默认XML和放大器;网页API,并为系列化和放大器JSON格式化;反序列化。
This should work for both default Xml & Json formatters of web api and for both serialization & deserialization.
[DataContract]
public class TestSerialization
{
[DataMember(Name = "field_one")]
public string ItemOne { get; set; }
[DataMember(Name = "field_two")]
public string ItemTwo { get; set; }
}
下面应该只有Json的格式,并为系列化和放大器工作;反序列化。
The following should work for Json formatter only and for both serialization & deserialization.
public class TestSerialization
{
[JsonProperty(PropertyName = "field_one")]
public string ItemOne { get; set; }
[JsonProperty(PropertyName = "field_two")]
public string ItemTwo { get; set; }
}
这篇关于的WebAPI - 反序列化和序列化替代属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!