C# JSON 的自动属性反序列化 [英] C# automatic property deserialization of JSON

查看:17
本文介绍了C# JSON 的自动属性反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些以 JSON 表示的 JavaScript 对象反序列化为适当的 C# 类.鉴于自动属性的良好特性,我更喜欢将它们放在这些类中,而不是只包含字段.不幸的是,.NET 序列化引擎(至少在默认情况下)完全忽略了反序列化的自动属性,只关心支持字段,这在 JavaScript 对象中显然不存在.

I need to deserialize some JavaScript object represented in JSON to an appropriate C# class. Given the nice features of automatic properties, I would prefer having them in these classes as opposed to just having fields. Unfortunately, the .NET serialization engine (at least, by default) totally ignores automatic properties on deserialization and only cares about the backing field, which is obviously not present in the JavaScript object.

鉴于有没有命名支持字段的标准方法,老实说我没有'甚至不想打扰让我们创建一个看起来像有 C# 支持字段的 JavaScript 对象"的方法,因为它听起来有点脏,如果我可以强制序列化引擎,我可以将 JavaScript 字段序列化为 C# 自动属性的唯一方法以某种方式忽略支持字段并直接使用该属性.不幸的是,我无法弄清楚这是如何完成的,或者是否可以完成.任何想法将不胜感激.

Given that there's no standard way to name backing fields and to be honest I don't even want to bother with the "let's create a JavaScript object that looks like it had C# backing fields" approach as it sounds a bit dirty, the only way I could serialize JavaScript fields to C# auto-properties if I could force the serialization engine to somehow ignore the backing field and use the property directly. Unfortunately, I can't figure out how this is done or if this can be done at all. Any ideas would be appreciated.

编辑:这是一个例子:

Javascript:

Javascript:

function Cat()
{
    this.Name = "Whiskers";
    this.Breed = "Tabby";
}
var cat = new Cat();

然后将其序列化为{Name: 'Whiskers'}".

This is then serialized to "{Name: 'Whiskers'}".

C# 类:

[Serializable()]
public class Cat
{
    public string Name { get; set; }
    public string Breed { get; set; }
}

以及失败的反序列化代码:

And the deserialization code, that fails:

new DataContractJsonSerializer(typeof(Cat)).ReadObject(inputStream);

从异常中可以看出它失败了,因为它正在寻找支持字段.

And it is apparent from the exception that it fails because it is looking for the backing field.

EDIT2:这是例外,如果有帮助的话(没有内部例外):

EDIT2: Here's the exception, if that helps (no inner exceptions):

System.Runtime.Serialization.SerializationException

System.Runtime.Serialization.SerializationException

"数据契约类型'Test.Cat'不能反序列化,因为必需的数据成员'k__BackingField, k__BackingField' 不是找到了."

"The data contract type 'Test.Cat' cannot be deserialized because the required data members '<Name>k__BackingField, <Breed>k__BackingField' were not found."

推荐答案

这里发生的事情是解串器正在尝试猜测您的支持字段的名称.您可以通过添加显式映射(DataContract/DataMember 属性)来解决这个问题:

What's happening here is the deserializer is trying to guess the name of your backing fields. You can solve this by adding explicit mappings (DataContract/DataMember attributes) like this:

[DataContract]
public class Cat
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Breed { get; set; }
}

这篇关于C# JSON 的自动属性反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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