簡體   English   中英

反序列化Json Web API響應-嵌套對象

[英]Deserialize Json Web API Response - Nested objects

我正在通過SSIS腳本組件獲得Web API JSON響應,該響應以以下格式返回:

    {
  "Success": true,
  "Response": {
    "Applications": [
      {
        "App_ID": 1638486,
        "App_Ref": "Test Example",
        "Status": "Complete",
        "Error_Code": null,
        "Error_Message": null,
        "Create_Dt": "2014-05-14 03:09:01.030 +00:00",
        "Modify_Dt": "2014-05-14 03:10:59.757 +00:00",
        "Client_Name": "Silver Chef",
        "Client_Code": "SLVC01",
        "Centrelink_Status": "Receiving_Logons"
      },
      {
        "App_ID": 1637906,
        "App_Ref": "SME Demo",
        "Status": "Complete",
        "Error_Code": null,
        "Error_Message": null,
        "Create_Dt": "2015-10-08 03:07:26.793 +00:00",
        "Modify_Dt": "2015-10-08 03:23:32.833 +00:00",
        "Client_Name": "Silver Chef",
        "Client_Code": "SLVC01",
        "Centrelink_Status": "Receiving_Logons"
      },
      {
        "App_ID": 1585286,
        "App_Ref": "Test",
        "Status": "Receiving_Logons",
        "Error_Code": null,
        "Error_Message": null,
        "Create_Dt": "2015-12-04 03:12:49.617 +00:00",
        "Modify_Dt": "2015-12-04 03:12:49.617 +00:00",
        "Client_Name": "Silver Chef",
        "Client_Code": "SLVC01",
        "Centrelink_Status": "Receiving_Logons"
      }
],
    "Current_Dt": "2016-11-11 01:01:01.743 +00:00",
    "Last_App_Dt": "2016-10-03 22:48:56.397 +00:00",
    "Count": 500,
    "Total": 1870
  }
}

我聲明了以下類:

     public class Application
        {
            public int App_ID { get; set; }
            public string App_Ref { get; set; }
            public string Status { get; set; }
            public int Error_Code { get; set; }
            public string Error_Message { get; set; }
            public DateTime Create_Dt { get; set; }
            public DateTime Modify_Dt { get; set; }
            public string Client_Name { get; set; }
            public string Client_Code { get; set; }
            public int Centrelink_Status { get; set; }

        }
        public class Response
        {
            public List<Application> Applications { get; set; }
            public string Current_Dt { get; set; }
            public string Last_App_Dt { get; set; }
            public int Count { get; set; }
            public int Total { get; set; }
        }

        public class RootObject
        {
            public bool Success { get; set; }
            public Response Response { get; set; }
        }

And this is the method that I am using to get the response. 
private RootObject GetWebServiceResult(string vAPIUrl)
    {

        string vAPIToken = Variables.APIToken;

        //Create Web Request
        HttpWebRequest apireq = (HttpWebRequest)WebRequest.Create(vAPIUrl);
        apireq.ContentType = "application/json";
        apireq.Method = "POST";

        string jsonPostStr = "{\"Settings\": {\"API_Token\": \"" + vAPIToken + "\"}, \"Payload\": {}}";
        byte[] postString = Encoding.UTF8.GetBytes(jsonPostStr);

        apireq.ContentLength = postString.Length;

        Stream jsonStream = apireq.GetRequestStream();

        jsonStream.Write(postString, 0, postString.Length);
        jsonStream.Close();

        // Get Web Response        
        HttpWebResponse apirsp = (HttpWebResponse)apireq.GetResponse();
        RootObject jsonResponse = null;

        Stream jsonRspStream = apirsp.GetResponseStream();
        string apiResponseString = null;

        using (StreamReader reader = new StreamReader(jsonRspStream)) 
        {
            apiResponseString = reader.ReadToEnd(); 
            Console.WriteLine(apiResponseString);
            reader.Close();
        }


        JavaScriptSerializer returnJson = new JavaScriptSerializer();

        //var serialJsonStr = returnJson.Serialize(apiResponseString);
        System.Windows.Forms.MessageBox.Show(apiResponseString);

        jsonResponse = returnJson.Deserialize<RootObject>(apiResponseString);

        return jsonResponse;

    }

我的問題是returnJson.Deserialize(apiResponseString); 似乎返回null,隨后使此操作失敗。

我想念什么? 我認為我在這個階段有點代碼盲。

提前致謝

Application類存在兩個問題:

  • 您已將Application.Error_Code定義為整數:

     public int Error_Code { get; set; } 

    但實際上,在JSON中,它具有空值:

     "Error_Code": null, 

    因此, Error_Code必須為引用類型( string )或可為空的值類型( int? ),具體取決於其在非null時的狀態。

  • 您已將Centrelink_Status定義為int ,但是在JSON中它是一個字符串:

     "Centrelink_Status": "Receiving_Logons" 

    因此,它在數據模型中也必須是字符串。

因此,您的Application類應如下所示:

public class Application
{
    public int App_ID { get; set; }
    public string App_Ref { get; set; }
    public string Status { get; set; }
    public int? Error_Code { get; set; } // Or string, if not numeric
    public string Error_Message { get; set; }
    public DateTime Create_Dt { get; set; }
    public DateTime Modify_Dt { get; set; }
    public string Client_Name { get; set; }
    public string Client_Code { get; set; }
    public string Centrelink_Status { get; set; }
}

如果JSON中可能有null值,您可能還想使那些DateTime屬性為可空。

順便說一句,當我嘗試反序列化此JSON時,拋出了異常,而不是返回null值:

System.InvalidOperationException was unhandled
  Message="Cannot convert null to a value type."
  Source="System.Web.Extensions"
  StackTrace:

在您的實際代碼中,您是否正在捕獲並吞下異常? 這是一個壞主意,恰恰是因為它傾向於隱藏諸如此類的錯誤。 至少,在調試時,無論何時拋出任何異常(包括一次機會異常),都應中斷-即使這不是默認行為。 請參閱使用調試器管理異常 如果發現某些經常拋出的異常類型與調試無關,則可以有選擇地重新忽略它們。 如果這樣做,則可以更輕松地找到此錯誤。 誠然,該錯誤不是很容易解釋,但確實給出了提示。 如果您要使用反序列化JSON,則錯誤消息會更加清晰:

Newtonsoft.Json.JsonSerializationException occurred
  Message="Error converting value {null} to type 'System.Int32'. Path 'Response.Applications[0].Error_Code', line 9, position 26."
  Source="Newtonsoft.Json"
  StackTrace:
       at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType) in C:\Development\Releases\Json\Working\Newtonsoft.Json\Working-Signed\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 986
  InnerException: System.InvalidCastException
       Message="Null object cannot be converted to a value type."
       Source="mscorlib"
       StackTrace:
            at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
            at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType) in C:\Development\Releases\Json\Working\Newtonsoft.Json\Working-Signed\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 979
       InnerException: 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM