gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:59:28 25 4
gpt4 key购买 nike

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

示例设置:

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 的所有类(class)。这需要在 ContractResolver 中完成——ShouldSerialize 属性就是一个例子,在我的真实场景中可能还有其他标准。我宁愿不必创建 ShouldSerializeCourse(如此处指定:http://james.newtonking.com/json/help/index.html?topic=html/ConditionalProperties.htm)

我似乎找不到在 ContractResolver 中覆盖哪个方法。我该怎么做?

最佳答案

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

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"
}
]
}
]

关于c# - 序列化为 JSON 时排除集合中的特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20955722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com