反序列化json响应

时间:2015-03-24 09:16:18

标签: c# json json.net

我正在使用API​​,除其他外还有这两个响应:

{
    "enrollDeviceErrorResponse": {
        "errorCode": "GRX-1056",
        "errorMessage": "DEP Reseller ID missing. 
        Enter a valid DEP Reseller ID and resubmit your request."
    }
}

{
    "enrollDeviceErrorResponse": [
      {
            "errorCode": "GRX-1056",
            "errorMessage": "DEP Reseller ID missing. 
            Enter a valid DEP Reseller ID and resubmit your request."
        },
        {
            "errorCode": "DEP-ERR-3003",
            "errorMessage": "Order information missing. T
            he transaction needs to have one or more valid orders. 
             Enter valid orders and resubmit your request."
        },
        {
            "errorCode": "DEP-ERR-3001",
            "errorMessage": "Transaction ID missing. 
            Enter a valid transaction ID and resubmit your request."
        }
    ]
}

我创建了一些可以反序列化为这些响应的类:

public class EnrollDeviceErrorRoot
{
    public EnrollDeviceErrorRoot()
    {
        this.EnrollDeviceErrorResponse = new EnrollDeviceErrorResponse();
    }

    public EnrollDeviceErrorResponse EnrollDeviceErrorResponse { get; set; }
}

public class EnrollDeviceErrorRoot
{
    public EnrollDeviceErrorRoot()
    {
        this.EnrollDeviceErrorResponse = new EnrollDeviceErrorResponse();
    }

    public EnrollDeviceErrorResponse EnrollDeviceErrorResponse { get; set; }
}

public class EnrollDeviceErrorResponse
{
    public string ErrorCode { get; set; }

    public string ErrorMessage { get; set; }
}

我很难想出一个很好的方法来确定我应该使用哪个类,具体取决于响应。我目前有这个失败的代码:

var multipleErrors = JsonConvert.DeserializeObject<EnrollDeviceErrorsRoot>(response);

if (multipleErrors.EnrollDeviceErrorResponse != null && multipleErrors.EnrollDeviceErrorResponse.Any())
{
    this.StatusCode = multipleErrors.EnrollDeviceErrorResponse.Select(x => x.ErrorCode).Aggregate((a, b) => a + ", " + b);
    this.StatusMessage = multipleErrors.EnrollDeviceErrorResponse.Select(x => x.ErrorMessage).Aggregate((a, b) => a + Environment.NewLine + b);
    this.HasErrors = true;

    return;
}

var singleError = JsonConvert.DeserializeObject<EnrollDeviceErrorRoot>(response);

if (!string.IsNullOrEmpty(singleError.EnrollDeviceErrorResponse.ErrorCode))
{
    this.StatusCode = singleError.EnrollDeviceErrorResponse.ErrorCode;
    this.StatusMessage = singleError.EnrollDeviceErrorResponse.ErrorMessage;
    this.HasErrors = true;

    return;
}

上述代码出错:

Newtonsoft.Json.JsonSerializationException : Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Atea.Dep.Core.Service.Models.EnrollDeviceErrorResponse]' 
because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, 
not a collection type like an array or List<T>) that can be deserialized from a JSON object. 
JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

当他们不知道从服务器回来的内容时,其他人如何处理这些反序列化的响应?我当然可以只看原始响应并确定这种方式,但还有其他更简洁的方法吗?我无法更改API,我不知道为什么只有一个带有一个或多个错误的列表的响应。

2 个答案:

答案 0 :(得分:2)

您可以使用

JObject.Parse(response)["enrollDeviceErrorResponse"].Type

确定响应的类型。在第一种情况下,它将是第二阵列中的对象。然后很容易继续进行适当的反序列化。

答案 1 :(得分:1)

您可以使用以下内容:

var output;
dynamic jObject = JsonConvert.DeserializeObject (outputAPI);
bool isArray = jObj.enrollDeviceErrorResponse.Type == JTokenType.Array;
bool isObject = jObj.enrollDeviceErrorResponse.Type == JTokenType.Object;
if(isObject)
   output = JsonConvert.DeserializeObject<EnrollDeviceErrorResponse>(outputAPI);
//else you will use the other class to deserialize the object