Excluding specific items in a collection when serializing to JSON

后端 未结 2 984
南旧
南旧 2020-12-03 23:12

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

Example setup:

public class Person
{
    public          


        
相关标签:
2条回答
  • 2020-12-03 23:38

    You should not put the logic into serializer. Instead filter the collection and then serialize it. In this case, you may use something like this

    Person.Courses = Person.Courses.Where(t=> t.ShouldSerialize == false);
    
    return Person;
    

    If you really need to add the contract resolver into your serializer you may do it in your Global.asax.cs (assuming you are using asp.net)

    0 讨论(0)
  • 2020-12-03 23:49

    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; }
    }
    

    Output:

    [
      {
        "Name": "John",
        "Courses": [
          {
            "Name": "Trigonometry"
          },
          {
            "Name": "History"
          }
        ]
      },
      {
        "Name": "Georgia",
        "Courses": [
          {
            "Name": "Spanish"
          },
          {
            "Name": "Geography"
          }
        ]
      }
    ]
    
    0 讨论(0)
提交回复
热议问题