You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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, the Code property will populate the shared _errorCode backing field.
  • When deserializing a response with "error_code", the ErrorCode property does the exact same thing.
  • The Message property handles the common message field present in both error structures.
  • The optional UnifiedErrorCode property 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 the System.Runtime.Serialization.Json namespace).
  • If you were using System.Text.Json instead, the approach would involve a custom converter or multiple [JsonPropertyName] attributes, but since you specifically asked for DataMemberAttribute, this is the right solution for your use case.

内容的提问来源于stack exchange,提问作者App2015

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:31:05