Asp.net-Mvc-4

使用 ReadAsAsync<T>() 反序列化複雜的 Json 對象

  • March 8, 2016

我想在 .net 4.0 的 mvc 項目中使用 ReadAsAsync()。結果為空。

如果我將uri輸入地址欄,chrome中的結果為(標籤名稱已更改):

&lt;ns2:MyListResponse xmlns:ns2="blablabla"&gt;
 &lt;customerSessionId&gt;xxcustomerSessionIdxx&lt;/customerSessionId&gt;
 &lt;numberOfRecordsRequested&gt;0&lt;/numberOfRecordsRequested&gt;
 &lt;moreResultsAvailable&gt;false&lt;/moreResultsAvailable&gt;
 &lt;MyList size="1" activePropertyCount="1"&gt;
   &lt;MySummary order="0"&gt;
     &lt;id&gt;1234&lt;/id&gt;
     &lt;name&gt;...&lt;/name&gt;
     .
     .   
   &lt;/MySummary&gt;
 &lt;/MyList&gt;
&lt;/ns2:MyListResponse&gt;

如果我在程式碼中使用該語句:

using (var client = new HttpClient())
{
    var response = client.GetAsync(apiUri).Result;
    var message = response.Content.ReadAsStringAsync().Result;

    var result1 = JsonConvert.DeserializeObject&lt;MyListResponse&gt;(message);
    var result2 = response.Content.ReadAsAsync&lt;MyListResponse&gt;().Result;
}

消息以字元串格式出現"{\"MyListResponse\":{\"customerSessionId\"...}",對應於 json 對象:

{"MyListResponse":
   {"customerSessionId":"xxcustomerSessionIdxx",
    "numberOfRecordsRequested":0,
    "moreResultsAvailable":false,
    "MyList":
       {"@size":"1",
        "@activePropertyCount":"1",
        "MySummary":
           {"@order":"0",
            "id":1234,
            "name":"...",
            .
            .
           }
       }
   }
} 

**result1 和 result2 的屬性為 null 或預設值。**類定義如下。我想將內容作為對象閱讀,但我不能。你有什麼建議來解決這個問題?我究竟做錯了什麼?提前致謝。

public class MySummary
{
   public int @Order { get; set; }
   public string Id { get; set; }
   public string Name { get; set; }
   .
   .
}

public class MyList
{
   public int @Size { get; set; }
   public int @ActivePropertyCount { get; set; }
   public MySummary MySummary{ get; set; }
}

public class MyListResponse
{
   public string CustomerSessionId { get; set; }
   public int NumberOfRecordsRequested { get; set; }
   public bool MoreResultsAvailable { get; set; }
   public MyList MyList { get; set; }
}

我將一個新類定義為:

public class ResponseWrapper
{
   public MyListResponse MyListResponse { get; set; }
}

然後我用這個包裝器,

var result1 = JsonConvert.DeserializeObject&lt;ResponseWrapper&gt;(message);
var result2 = response.Content.ReadAsAsync&lt;ResponseWrapper&gt;().Result;

然後它起作用了。我只需要 MySummary 對象,但我應該編寫更多類來使其工作。

閱讀您的解決方案後,我想出了一個不需要額外課程的解決方案:

   private static async Task&lt;U&gt; Execute&lt;U&gt;(HttpClient client, string path)
   {
       U output = default(U);

       HttpResponseMessage response = await client.GetAsync(path);

       if (response.IsSuccessStatusCode)
       {
           var jsonAsString = await response.Content.ReadAsStringAsync();
           output = JsonConvert.DeserializeObject&lt;U&gt;(jsonAsString);
       }
       else
       {
           throw new ApplicationException(string.Format("Response message is not OK. Issues in action: {0}", path));
       }

       return output;
   }

引用自:https://stackoverflow.com/questions/23576726