JSON

Json.Net学习笔记(十) 保持对象引用(2)

字号+ 作者:H5之家 来源:H5之家 2015-09-20 18:13 我要评论( )

在对象序列化器上设置PreserveReferencesHandling,将会改变所有对象被序列化和反序列化的方式。为了更加细致地控制对象和成员被序列化为一个引用,可以在JsonObjectAttribute, JsonArrayAttribute 和 JsonProperty

  在对象序列化器上设置PreserveReferencesHandling,将会改变所有对象被序列化和反序列化的方式。为了更加细致地控制对象和成员被序列化为一个引用,可以在JsonObjectAttribute, JsonArrayAttribute 和 JsonPropertyAttribute上使用IsReference 属性.

在JsonObjectAttribute, JsonArrayAttribute 上设置IsReference 为true,意味着Json序列化器总是会序列这个类型为一个引用。在JsonPropertyAttribute上设置IsReference为true将只序列化这个属性为一个引用。

 [JsonObject(IsReference = true)]
    public class EmployeeReference
    {
        public string Name { get; set; }
        public EmployeeReference Manager { get; set; }
    }

测试:

           List<EmployeeReference> empList = new List<EmployeeReference>();
            empList.Add(empRef);
            empList.Add(empRef);
            string empRefJson = JsonConvert.SerializeObject(empList, Formatting.Indented);
            Console.WriteLine(empRefJson);

输出结果:

[
  {
    "$id": "1",
    "Name": "IsReference",
    "Manager": null
  },
  {
    "$ref": "1"
  }
]

>IReferenceResolver

要想定制引用的生成方式,可以继承自IReferenceResolver接口来使用Json序列化器。

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • php CI 实战教程:[5]用curl获取json并解析

    php CI 实战教程:[5]用curl获取json并解析

    2016-02-26 17:00

  • 浅谈使用PHP开发微信支付的流程

    浅谈使用PHP开发微信支付的流程

    2016-02-13 15:00

  • php json时间格式转换

    php json时间格式转换

    2016-02-08 11:48

  • json 在线转换php

    json 在线转换php

    2016-02-05 16:00

网友点评