WebApi - 反序列化和序列化备用属性名称 [英] WebApi - Deserializing and serializing alternate property names

查看:58
本文介绍了WebApi - 反序列化和序列化备用属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何使用 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
  • 项目二

为了测试,这里有一个 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; }
}

到目前为止,我发现:

  • [DataMember(Name = "x")] 对任一方向的序列化都没有影响
  • [JsonProperty(Name = "x")] 在使用 JSON 时处理序列化(返回值).(这是一个 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"
  • field-one = "正确的 1"
  • field-two = "正确的 2"

我怎样才能做到这一点?

How can I achieve this?

推荐答案

您的某些发现/结论不正确...您可以尝试以下方法:

Some of your findings/conclusions are incorrect...you can try the following instead:

这应该适用于两者默认 Xml &Web 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆