我在一项服务下有多个API。这些API使用不同的Json负载。我想用属性和值创建一个模型类并进行设置。可以使用一个用于多个API的模型类来实现这一点。例如,我有一个采用Json ID和名称的API,以及另一个采用userID和颜色的API。将请求发送到需要这些数据的特定API时,如何调用要应用的特定attritube和值。我在我的Sendrequest中使用JsonConvert.SerializeObject(Model)
例如:
public class Model
{
public int id { get; set; }
public string name { get; set; }
public int userID { get; set; }
public string color { get; set; }
public Model()
{
this.id = 3;
this.name = "john";
this.userId = 101;
this.color = "blue"
}
}
您可以使用自定义ContractResolver
在序列化过程中选择性地包括或排除属性。您可以引入一个自定义属性,以指示模型中的哪些属性应包含在哪些API方法中。然后,让解析器查找那些属性,并忽略与您要为其序列化的API方法不匹配的模型属性。
属性代码:
[AttributeUsage(AttributeTargets.Property)]
public class UseWithApiMethodsAttribute : Attribute
{
public UseWithApiMethodsAttribute(params string[] methodNames)
{
MethodNames = methodNames;
}
public string[] MethodNames { get; private set; }
}
解析器代码:
public class SelectivePropertyResolver : DefaultContractResolver
{
public string ApiMethodName { get; private set; }
public SelectivePropertyResolver(string apiMethodName)
{
ApiMethodName = apiMethodName;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
if (member.MemberType == MemberTypes.Property)
{
var att = ((PropertyInfo)member).GetCustomAttribute<UseWithApiMethodsAttribute>(true);
if (att != null && !att.MethodNames.Contains(ApiMethodName))
{
prop.Ignored = true;
}
}
return prop;
}
}
然后,用这样的新属性标记模型,例如:
public class Model
{
[UseWithApiMethods("method1", "method3")]
public int id { get; set; }
[UseWithApiMethods("method1")]
public string name { get; set; }
[UseWithApiMethods("method2")]
public int userId { get; set; }
[UseWithApiMethods("method2")]
public string color { get; set; }
}
最后,创建一个使用解析器来序列化模型的辅助方法:
public static string SerializeForApiMethod(Model model, string methodName)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new SelectivePropertyResolver(methodName),
Formatting = Formatting.Indented
};
return JsonConvert.SerializeObject(model, settings);
}
例如这样称呼:
string json = SerializeForApiMethod(model, "method1");
这里是正在运行的演示:https://dotnetfiddle.net/vfXCqP