加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何命名c#类字段,以便能够使用无效字符反序列化json字段名称

发布时间:2020-12-15 08:43:36 所属栏目:百科 来源:网络整理
导读:我正在使用 JSON.NET反序列化我的一些 JSON响应. 到目前为止我一直很成功. 为了使JSON.NET正确反序列化对象,需要完全按照JSON中的方式调用类中的字段名称.问题是我有一些字段在他们的名字中有一些时髦的字符,我不能在C#中使用像{“(. 有谁知道如何重命名字段
我正在使用 JSON.NET反序列化我的一些 JSON响应.
到目前为止我一直很成功.
为了使JSON.NET正确反序列化对象,需要完全按照JSON中的方式调用类中的字段名称.问题是我有一些字段在他们的名字中有一些时髦的字符,我不能在C#中使用像{“(.

有谁知道如何重命名字段,以便正确映射?

这是一个有效的简短例子.

JSON输入:

{
    "contact_id": "","status": "Partial","is_test_data": "1","datesubmitted": "2013-10-25 05:17:06"
}

反序列化的类:

class DeserializedObject
{
    public string contact_id;
    public string status;
    public int is_test_data;
    public DateTime datesubmitted;
}

反序列化:

var deserialized = JsonConvert.DeserializeObject<DeserializedObject>(jsonInput);

这被正确映射.当我尝试处理以下字段时,问题开始:

{
    "contact_id": "","datesubmitted": "2013-10-25 05:17:06","[variable("STANDARD_GEOCOUNTRY")]": "Germany"
}

反序列化的类:

class Output
{
    public string contact_id;
    public string status;
    public int is_test_data;
    public DateTime datesubmitted;
    public string variable_standard_geocountry; // <--- what should be this name for it to work?
}

我将不胜感激任何帮助.

解决方法

使用JSON.NET,您只需要在属性上放置JsonProperty属性,例如:
class Output
{
    public string contact_id;
    public string status;
    public int is_test_data;
    public DateTime datesubmitted;

    [JsonProperty("[variable("STANDARD_GEOCOUNTRY")]")]
    public string variable_standard_geocountry; // <--- what should be this name for it to work?
}

现在将反序列化.这假定您的JSON使用这些引号正确格式化,例如:

{
    "contact_id": "","[variable("STANDARD_GEOCOUNTRY")]": "Germany"
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读