我可以帮您翻译以下内容,如下所示:
当
当
以此类推。
有没有办法做到这一点?
我以前用自定义属性制作过Xml版本,但在搜索
以下是我的Xml版本:
我正在寻找一种使用System.Text.Json
序列化对象的方法,但某些属性基于其他属性值被忽略。
例如:
public class Data
{
public string Type { get; set; }
public string A { get; set; }
public string B { get; set; }
public string BC { get; set; }
}
我使用这些数据填充了该类
var data = new Data
{
Type = "A",
A = "data A",
B = "data B",
BC = "data BC"
};
当
Type
的值为A
时,我想序列化属性Type
和A
。当
Type
的值为B
时,我想序列化属性Type
、B
和BC
。以此类推。
有没有办法做到这一点?
我以前用自定义属性制作过Xml版本,但在搜索
System.Text.Json
解决方案时,没有找到任何内容。以下是我的Xml版本:
public static bool HasAttribute<TAttribute>(
this PropertyInfo prop)
where TAttribute : Attribute
{
return prop.GetCustomAttributes(typeof(TAttribute), false).Any();
}
public static TValue GetAttributeValue<TAttribute, TValue>(
this PropertyInfo prop,
Func<TAttribute, TValue> valueSelector)
where TAttribute : Attribute
{
var att = prop.GetCustomAttributes(typeof(TAttribute), false).FirstOrDefault() as TAttribute;
if (att != null)
{
return valueSelector(att);
}
return default(TValue);
}
private void GenerateAttributeOverrides<T>(string type, XmlAttributeOverrides attributeOverrides, PropertyInfo[] properties)
{
foreach (var prop in properties)
{
var attributes = new XmlAttributes();
if (prop.HasAttribute<ShouldSerializeAttribute>())
{
var acceptedTypes = prop.GetAttributeValue<ShouldSerializeAttribute, string[]>(x => x.AcceptedTypes);
if (acceptedTypes.Contains(type))
{
attributes.XmlElements.Add(new XmlElementAttribute(prop.Name, prop.PropertyType);
}
else
{
attributes.XmlIgnore = true;
}
}
}
thanks in advance.