Jef*_*eff 6 .net c# json json.net
我试图"挑选"我要序列化的特定类型的集合中的哪些对象.
示例设置:
public class Person
{
public string Name { get; set; }
public List<Course> Courses { get; set; }
}
public class Course
{
...
public bool ShouldSerialize { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我需要能够排除Person.Courses集合中ShouldSerialize为false的所有课程.这需要在ContractResolver中完成 - ShouldSerialize属性就是一个例子,在我的实际场景中可能还有其他标准.我不想创建一个ShouldSerializeCourse(如这里指定的那样:http://james.newtonking.com/json/help/index.html?topic = html/ConditionsProperties.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; }
}
Run Code Online (Sandbox Code Playgroud)
输出:
[
{
"Name": "John",
"Courses": [
{
"Name": "Trigonometry"
},
{
"Name": "History"
}
]
},
{
"Name": "Georgia",
"Courses": [
{
"Name": "Spanish"
},
{
"Name": "Geography"
}
]
}
]
Run Code Online (Sandbox Code Playgroud)