Json。当readonly属性与对象引用一起使用时?

时间:2022-08-23 07:52:35

EDIT 2016-12-05: This was recognized as a bug and fixed: Readonly property corrupts normal property object references. #486

编辑2016-12-05:这被认为是一个错误并且修正了:只读属性会腐蚀普通属性对象引用。# 486

Original post:

原来的帖子:

I'm just starting out with Json.NET, but have encountered some strange behavior that seems like a bug.

我只是从Json开始。但是遇到了一些奇怪的行为,就像虫子一样。

If the Deserializer encounters an object reference ("$ref": "2") that was originally defined in a readonly property (get; only), it fails to deserialize and returns null instead.

如果反序列化器遇到最初在readonly属性中定义的对象引用(“$ref”:“2”)(get;仅),它无法反序列化并返回null。

Class

public class Parent
{
    public Child ReadOnlyChild
    {
        get
        {
            return Child;
        }
    }

    public Child Child {get; set;}
}
public class Child
{
}

Serialization:

序列化:

Parent p = new Parent() { Child = new Child() };
JsonConvert.SerializeObject(p, new JsonSerializerSettings()
{ Formatting = Formatting.Indented,
  PreserveReferencesHandling = PreserveReferencesHandling.Objects });

Serialized:

序列化:

{
  "$id": "1",
  "ReadOnlyChild": {
    "$id": "2",
  },
  "Child": {
    "$ref": "2"
  }
}

Deserialized (& reserialized to show the change):

反序列化(重新序列化以显示更改):

{
  "$id": "1",
  "ReadOnlyChild": null,
  "Child": null
}

Is this expected behavior, a bug, or am I missing something?

这是预期的行为,一个bug,还是我漏掉了什么?

Note that sometimes [JsonProperty(Order = #)] is needed to force the serializer to act on ReadOnlyChild first. Regardless, the above Serialized JSON block will fail to deserialize properly, even if the class has been modified to deserialize Child first.

注意,有时需要[JsonProperty(Order = #)]来强制序列化器先对ReadOnlyChild进行操作。无论如何,上面序列化的JSON块将无法正确反序列化,即使类已经被修改为先反序列化子块。

EDIT: The Child property being nulled is my concern, not ReadOnlyChild being somehow assigned a value by Json.NET

编辑:被取消的子属性是我关心的,不是ReadOnlyChild被Json.NET以某种方式分配值

Thanks!

谢谢!

1 个解决方案

#1


1  

Have you considered just preventing that property from being serialized by Json.Net?

您是否考虑过仅仅阻止该属性被Json.Net序列化?

public class Parent
{
    [JsonIgnore] 
    public Child ReadOnlyChild
    {
        get
        {
            return Child;
        }
    }

    public Child Child {get; set;}
}

#1


1  

Have you considered just preventing that property from being serialized by Json.Net?

您是否考虑过仅仅阻止该属性被Json.Net序列化?

public class Parent
{
    [JsonIgnore] 
    public Child ReadOnlyChild
    {
        get
        {
            return Child;
        }
    }

    public Child Child {get; set;}
}