C# JSON 反序列化 array/dictionary

C# JSON deserialization of array/dictionary

我必须使用 Web 服务 (json)。 我使用 JavaScriptSerializer 构建了一个序列化/反序列化通信。

在 99% 情况下它工作正常,但是... 错误详细信息返回如下:

{"result":"FAIL","error":{"error_code":1,"desc":"INVALID_DATA","details":{"city":["City cannot be blank."]}}}

处理我创建的 Class:

public class ErrorObj
{
    public int error_code { get; set; }
    public string desc { get; set; }
    public Dictionary<string, string[]> details { get; set; }
}

但是 somtethimes 'details' 是这样返回的:

{"result":"FAIL","error":{"error_code":1,"desc":"ERROR_OPTIONS","details":["Specifying a bank account"]}}

{"result":"FAIL","error":{"error_code":1,"desc":"INVALID_DATA","details":[]}}

要处理这个 class 应该是这样的:

public class ErrorObj
{
    public int error_code { get; set; }
    public string desc { get; set; }
    public string[] details { get; set; }
}

如何构建对象 (ErrorObj) 来处理所有错误消息?

反序列化代码:

public static T DeSerializeObjectFromJsonString<T>(string jsonString)
{
   T objectOut = default(T);
   Type outType = typeof(T);

   var obj = (T) new JavaScriptSerializer().Deserialize(jsonString, typeof(T));

  return obj;
}

错误信息:

System.InvalidOperationException : Type 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089], [System.String[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not supported for deserialization of an array.

您可以像这样使用模型对象。

public Dictionary<string, string[]> details { get; set; }, 只需使用 dynamic 而不是 Dictionary<string, string[]>.

因为json字符串detail不固定。

public class Error
{
    public int error_code { get; set; }
    public string desc { get; set; }
    public dynamic details { get; set; }
}

public class ErrorObj
{
    public string result { get; set; }
    public Error error { get; set; }
}

如果你想知道,你得到了哪个json?

您可以使用 detail.GetType()。检查类型是否为数组。

就这么简单

string DictJson = "{\"result\":\"FAIL\",\"error\":{\"error_code\":1,\"desc\":\"INVALID_DATA\",\"details\":{\"city\":[\"City cannot be blank.\"]}}}";

string ArrayJson = "{\"result\":\"FAIL\",\"error\":{\"error_code\":1,\"desc\":\"ERROR_OPTIONS\",\"details\":[\"Specifying a bank account\"]}}";

ErrorObj errorobj = DeSerializeObjectFromJsonString<ErrorObj>(ArrayJson);

if (errorobj.error.details.GetType().IsArray)
{
    //receive array detail
}
else
{
    //receive Dictionary<> detail
}

这很奇怪,因为网络服务 属性 不应该在不同的结果中更改它的类型。

您可以通过更改 details 类型来处理它。

public JToken details { get; set; }

我还建议您坚持 C# 命名约定并为所有属性使用 JsonProperty 属性。

[JsonProperty("details")]
public JToken Details { get; set; }