我目前拥有一组api,并且正在实现某些API的v2。控制器级别我将URL设置为/ v2 /。我有要求其中一个API响应是
Http响应
{
"prd":"product name"
}
Product.cs
public class ProductInfo
{
[JsonProperty("prd")]
public string ProductName { get; set;}
}
在API的version2中,我想将JsonProperty(“ prd”)更改为JsonProperty(“ product_name”)。如何根据API版本动态更改属性名称和忽略某些属性。我不想复制服务层
答案 0 :(得分:-2)
您可以使用Json.Net中的自定义ContractResolver实现此目的。在这里,我创建了一个简单的演示示例。您可以根据API版本控制条件执行它。
void Main()
{
var productInfo = new ProductInfo();
productInfo.ProductName = "Product Name";
var jsonResolver = new PropertyRenameSerializerContractResolver();
jsonResolver.RenameProperty(typeof(ProductInfo), "prd", "product_name");
var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = jsonResolver;
var json = JsonConvert.SerializeObject(productInfo, serializerSettings);
Console.WriteLine(json);
}
public class ProductInfo
{
[JsonProperty("prd")]
public string ProductName { get; set; }
}
public class PropertyRenameSerializerContractResolver : DefaultContractResolver
{
private readonly Dictionary<Type, Dictionary<string, string>> _renames;
public PropertyRenameSerializerContractResolver()
{
_renames = new Dictionary<Type, Dictionary<string, string>>();
}
public void RenameProperty(Type type, string propertyName, string newJsonPropertyName)
{
if (!_renames.ContainsKey(type))
_renames[type] = new Dictionary<string, string>();
_renames[type][propertyName] = newJsonPropertyName;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (IsRenamed(property.DeclaringType, property.PropertyName, out var newJsonPropertyName))
property.PropertyName = newJsonPropertyName;
return property;
}
private bool IsRenamed(Type type, string jsonPropertyName, out string newJsonPropertyName)
{
Dictionary<string, string> renames;
if (!_renames.TryGetValue(type, out renames) || !renames.TryGetValue(jsonPropertyName, out newJsonPropertyName))
{
newJsonPropertyName = null;
return false;
}
return true;
}
}
该程序的输出将如下所示:
{"product_name":"Product Name"}
我已在与您的方案匹配的方案之一中使用了此功能。有关更多详细信息,请参阅以下文章。