您可以使用
JsonSerializerSettings,ContractResolver和NamingStrategy。
public class ErrorDetails{ public int Id { get; set; } public string ErrorMessage { get; set; }}var json = "{'Id': 1,'error_message': 'An error has occurred!'}";
对于反序列化,您可以使用
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);
jsonNew =“ {‘Id’:1,’ErrorMessage’:’发生错误!’}”
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)