序列化为 JSON 时排除集合中的特定项目

Excluding specific items in a collection when serializing to JSON(序列化为 JSON 时排除集合中的特定项目)

本文介绍了序列化为 JSON 时排除集合中的特定项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试挑选"我想要序列化的特定类型集合中的哪些对象.

I am trying to "cherry-pick" which objects in a collection of a specific type I want to serialize.

示例设置:

public class Person
{
    public string Name { get; set; }

    public List<Course> Courses { get; set; }
}

public class Course
{
    ...

    public bool ShouldSerialize { get; set; }
}

我需要能够排除 Person.Courses 集合中 ShouldSerialize 为 false 的所有课程.这需要在 ContractResolver 中完成——ShouldSerialize 属性就是一个例子,在我的真实场景中可能还有其他标准.我宁愿不必创建 ShouldSerializeCourse (如此处指定:http://james.newtonking.com/json/help/index.html?topic=html/ConditionalProperties.htm)

I need to be able to exclude all the courses in the Person.Courses collection where ShouldSerialize is false. This needs to be done from within the ContractResolver - the ShouldSerialize property is an example, in my real scenario there may be other criteria. I'd prefer not having to create a ShouldSerializeCourse (as specified here: http://james.newtonking.com/json/help/index.html?topic=html/ConditionalProperties.htm )

我似乎无法在 ContractResolver 中找到要覆盖的方法.我该怎么办?

I can't seem to find out which method to override in the ContractResolver. How would I go about this?

推荐答案

我认为您不能使用 ContractResolver 过滤列表,但您可以使用自定义 JsonConverter 来过滤.这是一个例子:

I don't think you can filter a list using a ContractResolver, but you could do it using a custom JsonConverter. Here is an example:

class Program
{
    static void Main(string[] args)
    {
        List<Person> people = new List<Person>
        {
            new Person 
            {
                Name = "John",
                Courses = new List<Course>
                {
                    new Course { Name = "Trigonometry", ShouldSerialize = true },
                    new Course { Name = "History", ShouldSerialize = true },
                    new Course { Name = "Underwater Basket Weaving", ShouldSerialize = false },
                }
            },
            new Person
            {
                Name = "Georgia",
                Courses = new List<Course>
                {
                    new Course { Name = "Spanish", ShouldSerialize = true },
                    new Course { Name = "Pole Dancing", ShouldSerialize = false },
                    new Course { Name = "Geography", ShouldSerialize = true },
                }
            }
        };

        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.Converters.Add(new CourseListConverter());
        settings.Formatting = Formatting.Indented;

        string json = JsonConvert.SerializeObject(people, settings);
        Console.WriteLine(json);
    }
}

class CourseListConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<Course>));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, ((List<Course>)value).Where(c => c.ShouldSerialize).ToArray());
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

public class Person
{
    public string Name { get; set; }
    public List<Course> Courses { get; set; }
}

public class Course
{
    public string Name { get; set; }
    [JsonIgnore]
    public bool ShouldSerialize { get; set; }
}

输出:

[
  {
    "Name": "John",
    "Courses": [
      {
        "Name": "Trigonometry"
      },
      {
        "Name": "History"
      }
    ]
  },
  {
    "Name": "Georgia",
    "Courses": [
      {
        "Name": "Spanish"
      },
      {
        "Name": "Geography"
      }
    ]
  }
]

这篇关于序列化为 JSON 时排除集合中的特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:序列化为 JSON 时排除集合中的特定项目

基础教程推荐