我正在从如下所示的Web API接收JSON数据:
[ { "id": 1 "error_message": "An error has occurred!" } ]
我将此数据反序列化为以下类型的对象:
public class ErrorDetails { public int Id { get; set; } [JsonProperty("error_message")] public string ErrorMessage { get; set; } }
稍后在我的应用程序中,我想再次将ErrorDetails对象序列化为JSON,但使用属性名称ErrorMessage代替error_message。因此结果将如下所示:
ErrorMessage
error_message
[ { "Id": 1 "ErrorMessage": "An error has occurred!" } ]
有什么简单的方法可以使用Json.Net完成此操作?也许使用自定义解析器和一些属性,例如:
public class ErrorDetails { public int Id { get; set; } [SerializeAs("ErrorMessage")] [DeserializeAs("error_message")] public string ErrorMessage { get; set; } }
但是解析器不会告诉我何时进行序列化或反序列化。
您可以使用JsonSerializerSettings,ContractResolver和NamingStrategy。
JsonSerializerSettings
public class ErrorDetails { public int Id { get; set; } public string ErrorMessage { get; set; } } var json = "{'Id': 1,'error_message': 'An error has occurred!'}";
对于反序列化,您可以使用SnakeCaseNamingStrategy。
SnakeCaseNamingStrategy
var dezerializerSettings = new JsonSerializerSettings { ContractResolver = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() } }; var obj = JsonConvert.DeserializeObject<ErrorDetails>(json, dezerializerSettings);
要再次序列化对象,您不必更改,JsonSerializerSettings因为默认情况下将使用属性名称。
var jsonNew = JsonConvert.SerializeObject(obj);
jsonNew =“ {‘Id’:1,’ErrorMessage’:’发生错误!’}”
或者,您可以创建合同解析器,该解析器可以决定要使用的名称。然后,您可以决定何时要对pascal大小写名称格式或带下划线的格式进行反序列化和序列化。
public class CustomContractResolver : DefaultContractResolver { public bool UseJsonPropertyName { get; } public CustomContractResolver(bool useJsonPropertyName) { UseJsonPropertyName = useJsonPropertyName; } protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var property = base.CreateProperty(member, memberSerialization); if (!UseJsonPropertyName) property.PropertyName = property.UnderlyingName; return property; } } public class ErrorDetails { public int Id { get; set; } [JsonProperty("error_message")] public string ErrorMessage { get; set; } } var json = "{'Id': 1,'error_message': 'An error has occurred!'}"; var serializerSettings = new JsonSerializerSettings() { ContractResolver = new CustomContractResolver(false) }; var dezerializerSettings = new JsonSerializerSettings { ContractResolver = new CustomContractResolver(true) }; var obj = JsonConvert.DeserializeObject<ErrorDetails>(json, dezerializerSettings); var jsonNew = JsonConvert.SerializeObject(obj, serializerSettings);