C#中用DataMemberAttribute反序列化多名称API错误返回
Handling Dual Error JSON Structures with DataMemberAttribute in C#
The issue with your initial code is that you can't assign multiple Name values to a single DataMemberAttribute—each attribute instance only accepts one name. But don't worry, we can work around this by using two separate properties that both map to the same backing field, each targeting one of the JSON keys we need to handle.
Here's a clean, working implementation:
using System.Runtime.Serialization; [DataContract] public class Error { private string _errorCode; [DataMember(Name = "code")] public string Code { get => _errorCode; set => _errorCode = value; } [DataMember(Name = "error_code")] public string ErrorCode { get => _errorCode; set => _errorCode = value; } [DataMember(Name = "message")] public string Message { get; set; } // Optional: Get the error code in one consistent place public string UnifiedErrorCode => _errorCode; }
How this works:
- When deserializing a response with the
"code"field, theCodeproperty will populate the shared_errorCodebacking field. - When deserializing a response with
"error_code", theErrorCodeproperty does the exact same thing. - The
Messageproperty handles the common message field present in both error structures. - The optional
UnifiedErrorCodeproperty gives you a single, reliable way to access the error code without having to check which property was populated.
Testing with your sample JSONs:
For your first error JSON:
{ "error_code": "234", "message": "Api Key is required" }
After deserialization, error.UnifiedErrorCode will be "234" and error.Message will be "Api Key is required".
For the second error JSON:
{ "code": "NotFound", "message": "Could not find the resource" }
error.UnifiedErrorCode will be "NotFound" and error.Message will be "Could not find the resource".
Quick notes:
- This works seamlessly with
DataContractJsonSerializer(from theSystem.Runtime.Serialization.Jsonnamespace). - If you were using
System.Text.Jsoninstead, the approach would involve a custom converter or multiple[JsonPropertyName]attributes, but since you specifically asked forDataMemberAttribute, this is the right solution for your use case.
内容的提问来源于stack exchange,提问作者App2015
相关产品推荐
相关产品推荐

