簡體   English   中英

xamarin forms 將值“[json]”轉換為列表時出錯

[英]xamarin forms error converting values “[json]” to list

我正在學習 Xamarin 來構建跨平台的移動應用程序。 為了從 SQL 服務器獲取數據,我創建了一個 web API 並將其托管在我的 LAN 網絡中。 我已經對其進行了測試,它可以按預期完美運行。

編輯添加 Json Json 是

[{"Id":1,"FirstName":"D","LastName":"M","Company":"MD"},{"Id":2,"FirstName":"D","LastName":"S","Company":"DM"},{"Id":6,"FirstName":"MD","LastName":"","Company":"MD"},{"Id":8,"FirstName":"DM","LastName":"D","Company":""}]

xamarin.forms中,我有一個列表,我將在其中反序列化 JSON 並將其分配為 ItemsSource。

問題是無論我嘗試以何種方式反序列化 JSON,它都會在轉換中引發錯誤。

編輯我僅在嘗試使用 DataContractJsonSerializer 反序列化時使用了 DataContract 屬性。

這是我的 JSON 的采購訂單 class,

[DataContract]
public class Employee
{
    [DataMember]
    [JsonProperty("Id")]
    public int Id { get; set; }

    [DataMember]
    [JsonProperty("FirstName")]
    public string FirstName { get; set; }

    [DataMember]
    [JsonProperty("LastName")]
    public string LastName { get; set; }

    [DataMember]
    [JsonProperty("Company")]
    public string Company { get; set; }
}

以下是一些用於反序列化 JSON 的代碼,

var response = await httpClient.GetAsync(Url);
if (response.IsSuccessStatusCode)
{
    var content = await response.Content.ReadAsStringAsync();
    var Employees = JsonConvert.DeserializeObject<Employee>(content);
    empListView.ItemsSource = Employees;
}
else
{
    await DisplayAlert("Failed", "Connection Failed", "OK");
}

它導致了一個錯誤

錯誤圖像

為了解決這個問題,我將上面的代碼修改為,

List<Employee> Employees = JsonConvert.DeserializeObject<List<Employee>>(content);

它導致了同樣的錯誤,我嘗試使用數組,

Employee[] Employees = JsonConvert.DeserializeObject<Employee[]>(content);

在另一個關於此堆棧溢出中相同問題的討論中,我找到了一個代碼並嘗試過,

using (var web = new WebClient())
{
    var response = web.DownloadString(Url);
    Employee[] emp;
    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(response)))
    {
        var serializer = new DataContractJsonSerializer(typeof(Employee[]));
        emp = serializer.ReadObject(stream) as Employee[];
    }
    empListView.ItemsSource = emp;
}

但這也無濟於事。 誰能幫我解決這個問題?

代替:

List<Employee> Employees = JsonConvert.DeserializeObject<List<Employee>>(content);

嘗試:

List<Employee> Employees = JsonConvert.DeserializeObject<List<Employee>>(content.ToString());

希望能幫助到你。 讓我知道!

I think the problem is in the JSON-string from the response, my guess is that you serialize the object to JSON before returning it, the API should serialize objects to JSON by default. 嘗試從 API 返回 object。

暫無
暫無

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

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