使用不同的名称通过Json.Net进行序列化和反序列化

使用不同的名称通过Json.Net进行序列化和反序列化,第1张

使用不同的名称通过Json.Net进行序列化和反序列化

您可以使用

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’:’发生错误!’}”



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5642569.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存