反序列化时如何从 json 中删除 k__BackingField [英] How to remove k__BackingField from json when Deserialize

查看:22
本文介绍了反序列化时如何从 json 中删除 k__BackingField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将 xml 文件序列化为 .net c# 对象后,我在返回的 json 中获取了 k_BackingField.

I am getting the k_BackingField in my returned json after serializing a xml file to a .net c# object.

我已将 DataContract 和 DataMember 属性添加到 .net c# 对象,但随后在客户端的 json 上什么也没有.

I've added the DataContract and the DataMember attribute to the .net c# object but then I get nothing on the json, client end.

[XmlRoot("person")]
[Serializable]
public class LinkedIn
{
    [XmlElement("id")]
    public string ID { get; set; }

    [XmlElement("industry")]
    public string Industry { get; set; }

    [XmlElement("first-name")]
    public string FirstName { get; set; }

    [XmlElement("last-name")]
    public string LastName { get; set; }
    [XmlElement("headline")]
}

返回的json示例:

home: Object
<FirstName>k__BackingField: "Storefront"
<LastName>k__BackingField: "Doors"

推荐答案

如果类可以用于序列化,实际上不推荐使用自动属性语法.原因是支持字段是由编译器生成的,每次编译代码时都会不同.即使不对类进行任何更改(只需重新编译代码),这也会导致不兼容问题.

Automatic Property syntax is actually not recommended if the class can be used in serialization. Reason being the backing field is generated by compiler which can be different each time code is compiled. This can cause incompatibility issues even if no change is made to the class (just recompiling the code).

我认为在这种情况下应用 DataMember 属性将解决该问题.但如果需要在序列化中使用该类,我会建议使用完整的属性语法.

I think applying DataMember attribute will fix the issue in this case. But I would recommend to use full property syntax, if the class needs to be used in serialization.

这篇关于反序列化时如何从 json 中删除 k__BackingField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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