- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试“挑选”我想要序列化的特定类型集合中的哪些对象。
示例设置:
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/
出于好奇,我尝试了一些原型(prototype)制作,但似乎只允许在第一个位置使用子例程的原型(prototype) &。 当我写作时 sub test (&$$) { do_somethin
我需要开发一个类似于 Android Play 商店应用程序或类似 this app 的应用程序.我阅读了很多教程,发现几乎每个教程都有与 this one 类似的例子。 . 我已经开始使用我的应用程
考虑一个表示“事件之间的时间”的列: (5, 40, 3, 6, 0, 9, 0, 4, 5, 18, 2, 4, 3, 2) 我想将这些分组到 30 个桶中,但桶会重置。期望的结果: (0, 1,
我是一名优秀的程序员,十分优秀!