如何在 JSON 模型类中使用保留关键字作为标识符? [英] How can I use a reserved keyword as an identifier in my JSON model class?

查看:30
本文介绍了如何在 JSON 模型类中使用保留关键字作为标识符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前从未使用过 Web API,但我需要一个可以接受/返回 JSON 对象的 Web 服务,使用它似乎是一件合理的事情.它看起来很简单(如果不是我的目的有点矫枉过正的话),但我需要处理的数据结构看起来像:

I have never used Web API before, but I need a web service that will accept/return JSON objects and using this seemed like a reasonable thing. It looked pretty simple (if not a bit of overkill for my purposes), but a data structure I need to deal with looks something like:

{
    "values":["foo", "bar"],
    "default":"bar"
}

所以我去创建一个模型对象:

And so I went to make a Model object:

class DropDownValues {
    public string[] values { get; set; }
    public string default { get; set; }
}

问题是默认值似乎是受保护的关键字.一定有办法解决这个问题,对吧?

Problem is that default seems to be a protected keyword. There must be some way to get around that, right?

推荐答案

我建议采取不同的方式.尽可能保持 C# 对象模型的标准(我不会使用 @ 符号和 C# 关键字 作为属性名称).

I would suggest to go different way. Keep your C# object model as much standard as possible (I wouldn't use @ sign and C# keywords as property name).

我们可以将序列化 (JSON) 世界和 C# 对象分开 - 只需使用 Json.NET 功能即可.

We can separate the serialized (JSON) world and C# objects - just by using the Json.NET features.

最简单的使用方法之一是使用 Attribute 进行装饰:

One of the simpliest to use is decoration with Attribute:

[JsonProperty(PropertyName = "default")]
public string DefaultValue { get; set; }

在这种情况下,我们必须在项目中引用 Newtonsoft.Json.如果必须是 POCO,我们可以引入从 DefaultContractResolver 派生的 CustomResolver 并在那里定义这些转换...

In this case we have to reference Newtonsoft.Json in the project. If it must be POCO, we can introduce CustomResolver derrived from DefaultContractResolver and define these conversions there...

但在这种情况下,关注点分离是一种更纯粹的解决方案,我会说

But separation of concern in this case is a bit more pure solution, I would say

JSON 合同解析器草案 (见评论)

重要说明:Newtonsoft.Json 是 Web API 的一部分.它不仅是一个开源软件,甚至 MS 团队也将其作为核心 JSON 序列化程序.

Important NOTE: Newtonsoft.Json is part of the Web API. Not only it is an open source, but even MS team bet on that as a core JSON serializer.

1) Newtonsoft.Json(作为 Web.API 的一部分)已安装在您的解决方案中.所以你不必单独下载 (nuget).它始终位于您的 packages 文件夹中.因此,使用属性只是添加引用.它在那里...

1) Newtonsoft.Json (as a part of the Web.API) is already installed in your solution. So you do not have to downloaded (nuget) separately. It would always be in your packages folder. So, to use the attribute is just adding the reference. It is there...

2) 有一个小草案如何做属性的东西,同时保持 POCO.正如我在这里尝试解释的那样:POCO、行为和持久性无知,以保持 POCO(例如,我们确实从分层架构中获利)使用数据层上的 NHibernate),我们可以Contract Resolver替换属性.我们的 POCO 库不需要引用任何东西

2) There is a small draft how to do the attribute stuff, while keeping the POCO. As I've tried explain here: POCO's, behavior and Peristance Igorance, to keep POCO (e.g. we do profit from layered Architecture with NHibernate on a data layer), we can replace attributes with a Contract Resolver. Our POCO library does not have to reference anything

我们只需要扩展服务层:

We just have to do extend the service layer:

public class MyResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(
         MemberInfo member,
         MemberSerialization memberSerialization)
    {

        var jProperty = base.CreateProperty(member, memberSerialization);

        var propertyInfo = member as PropertyInfo;
        if (propertyInfo == null)
        {
            return jProperty;
        }

        // just adjust in case if Property name is DefaultValue
        var isDefaultValueProeprty =
                  propertyInfo.Name.Equals("DefaultValue");

        if(isDefaultValueProeprty)
        {
            jProperty.PropertyName = "default";
        }

        return jProperty;
    }
    ...

通过这种方式,我们向 serailizer 提供了与 [JsonPropertyAttribute] 相同的信息.

This way we've provided the same information to serailizer as with the [JsonPropertyAttribute].

现在,我们只需要使用它.有很多方法(例如全局),但我们只能为控制器执行此操作:

Now, we just have to use it. There are many ways (e.g. global) but we can do it for a controller only:

protected override void Initialize(HttpControllerContext context)
{
  base.Initialize(context);

  var jSettings = context.Configuration.Formatters.JsonFormatter.SerializerSettings;
  jSettings.ContractResolver = MyResolver;
}

这篇关于如何在 JSON 模型类中使用保留关键字作为标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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