如何仅在序列化时修改C#对象的JSON属性名称?
解决Json序列化与反序列化属性名称不一致的问题
你需要在反序列化时读取response_code,序列化时输出responseCode,可以用以下两种方法实现:
方法一:自定义序列化配置(推荐)
保持原有类结构不变,通过修改序列化配置实现名称切换:
1. 定义APIResponse类
public class APIResponse { [JsonProperty("response_code")] public HttpStatusCode ResponseCode { get; set; } }
2. 反序列化(读取response_code)
直接用默认配置反序列化即可:
var inputJson = "{\"response_code\":23}"; var response = JsonConvert.DeserializeObject<APIResponse>(inputJson);
3. 序列化(输出responseCode)
创建自定义的序列化配置,强制使用驼峰命名并忽略JsonProperty指定的反序列化名称:
var serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver { NamingStrategy = new CamelCaseNamingStrategy { OverrideSpecifiedNames = false } } }; var outputJson = JsonConvert.SerializeObject(response, serializerSettings); // 输出结果:{"responseCode":23}
方法二:拆分属性配合条件序列化
通过拆分属性,用ShouldSerialize方法控制序列化时输出的字段:
public class APIResponse { private HttpStatusCode _responseCode; // 仅用于反序列化,读取JSON中的response_code [JsonProperty("response_code")] public HttpStatusCode ResponseCodeForDeserialize { get => _responseCode; set => _responseCode = value; } // 仅用于序列化,输出为responseCode [JsonProperty("responseCode")] public HttpStatusCode ResponseCodeForSerialize { get => _responseCode; set => _responseCode = value; } // 序列化时不输出反序列化用的属性 public bool ShouldSerializeResponseCodeForDeserialize() => false; }
使用时,反序列化和序列化都用默认配置即可,序列化时只会输出responseCode字段。
内容的提问来源于stack exchange,提问作者Yener
相关产品推荐
相关产品推荐

