【问题标题】:How to convert Json object with ref attribute into c# class? [duplicate]如何将具有 ref 属性的 Json 对象转换为 c# 类? [复制]
【发布时间】:2020-12-17 15:49:01
【问题描述】:

我有下面的 json 对象要转换为 c# 类。

{
   "Token": “Token”,
   "ref": 1 
}

转换后的c#类如下。

public class ABC
{
public string Token{get;set;}
public int ref{get;set;}
}

但我从 c# 收到以下错误消息。

成员修饰符'ref'必须在成员类型和名称之前

如何使用 ref 属性正确地将 JSON 转换为 c# 类?

提前致谢。

【问题讨论】:

    标签: c# asp.net json


    【解决方案1】:

    Newtonsoft.Json,你可以这样做:

    public class ABC
    {
        public string Token{get;set;}
        [JsonProperty("ref")]
        public int Ref{get;set;}
    }
    

    如果您不想这样做或不能这样做,请使用:

    public class ABC
    {
        public string Token { get; set; }
        public int @ref {get; set; }
    }
    

    由于ref 是C# 关键字,您可以添加@ 符号,以便将其用作属性名称。

    var thing = new ABC { @ref = 0 };
    thing.@ref = 5;
    

    您的模型将被序列化,就好像它被定义为ref

    【讨论】:

    • 谢谢。 [JsonProperty("ref")] 成功了!
    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多