使用不同的名称通过Json.Net进行序列化和反序列化 [英] Use different name for serializing and deserializing with Json.Net

查看:101
本文介绍了使用不同的名称通过Json.Net进行序列化和反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从如下所示的Web API接收JSON数据:

I am receiving JSON data from a web API that looks like this:

[
  {
    "id": 1
    "error_message": "An error has occurred!"
  }
]

我将此数据反序列化为以下类型的对象:

I deserialize this data to objects of the following type:

public class ErrorDetails
{
    public int Id { get; set; }

    [JsonProperty("error_message")]
    public string ErrorMessage { get; set; }
}

稍后在我的应用程序中,我想再次将ErrorDetails对象序列化为JSON,但要使用属性名称ErrorMessage而不是error_message.因此结果将如下所示:

Later in my application I would like to serialize the ErrorDetails object again to JSON but using the property name ErrorMessage instead of error_message. So the result would look like this:

[
  {
    "Id": 1
    "ErrorMessage": "An error has occurred!"
  }
]

我是否可以通过Json.Net轻松实现这一目标?也许使用自定义解析器和一些属性,如:

Is there an easy way I can accomplish this with Json.Net? Perhaps using a custom resolver and some attributes like:

public class ErrorDetails
{
    public int Id { get; set; }

    [SerializeAs("ErrorMessage")]
    [DeserializeAs("error_message")]
    public string ErrorMessage { get; set; }
}

但是当我进行序列化或反序列化时,解析程序不会告诉我.

But the resolver doesn't tell me when I'm serializing or deserializing.

推荐答案

您可以使用JsonSerializerSettings,ContractResolver和NamingStrategy.

You can make use of the JsonSerializerSettings, the ContractResolver and the 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.

For dezerialization you could use the SnakeCaseNamingStrategy.

var dezerializerSettings = new JsonSerializerSettings
{
    ContractResolver = new DefaultContractResolver
    {
        NamingStrategy = new SnakeCaseNamingStrategy()
    }
};
var obj = JsonConvert.DeserializeObject<ErrorDetails>(json, dezerializerSettings);

要再次序列化对象,您不必更改JsonSerializerSettings,因为默认情况下将使用属性名称.

To serialize the object again you dont have to change the JsonSerializerSettings as the default will use the property name.

var jsonNew = JsonConvert.SerializeObject(obj);

jsonNew ="{'Id':1,'ErrorMessage':'发生错误!'}"

jsonNew = "{'Id': 1,'ErrorMessage': 'An error has occurred!'}"


或者您可以创建合同解析器,该合同解析器可以决定要使用的名称.然后,您可以决定是要使用pascal大小写名称格式还是带下划线的格式,何时进行反序列化和序列化.


Or you could create a contract resolver which can decide which name to use. Then you can decide when you dezerialize and serialize if you want to use the pascal case name format or the one with the underscore.

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':'发生错误!'}"

jsonNew = "{'Id': 1,'ErrorMessage': 'An error has occurred!'}"

这篇关于使用不同的名称通过Json.Net进行序列化和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆