使用Newtonsoft.Json Xamarin C#反序列化JSON Got Error

时间:2016-07-13 11:34:05

标签: c# json xamarin json.net

我在尝试反序列化JSON时遇到错误,因为我的JSON不是单个数据(它就像数组一样),然后我尝试使用List<>但它说Cannot convert from System.Collections.Generic.List<string>' to 'string

这是JSON数据的示例:

[
    {
        "no":"73",
        "nama":"Nicosia Lady",
        "uk":"37 - 40",
        "fotou":"73-u.jpg",
        "bahan":"Canvas",
        "poin":"120",
        "harga":"119900.00",
        "warna1":"Green",
        "warna2":"Grey",
        "warna3":"Navy",
        "warna4":"Maroon",
        "warna5":null
    },
    {
        "no":"78",
        "nama":"Minsk Man",
        "uk":"38 - 43",
        "fotou":"78-u.jpg",
        "bahan":"Canvas",
        "poin":"140",
        "harga":"141800.00",
        "warna1":"Black White",
        "warna2":"Brown BCoffee",
        "warna3":"Navy Orange",
        "warna4":"Grey Navy",
        "warna5":null
    },
]

这是我的班级:

class user
    {
        public int no { get; set; }
        public string nama { get; set; }
        public string uk { get; set; }
        public string fotou { get; set; }
        public string bahan { get; set; }
        public int poin { get; set; }
        public int harga { get; set; }
        public string warna1 { get; set; }
        public string warna2 { get; set; }
        public string warna3 { get; set; }
        public string warna4 { get; set; }
        public string warna5 { get; set; }
    }

这是剧本:

button.Click += async (sender, e) =>
           {
 string url = "http://myapi.com/url/example/";
 List<user> userList = JsonConvert.DeserializeObject<List<user>>(await FetchUserAsync(url));//got error on await FetchUserAsync(url)

           // txtHasil.Text = userList.nama;
        };

和此:

private async Task<List<string>> FetchUserAsync(string url)
        {
            // Create an HTTP web request using the URL:
             HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
            //HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = "GET";

            // Send the request to the server and wait for the response:
            using (WebResponse response = await request.GetResponseAsync())
            {
                // Get a stream representation of the HTTP web response:
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    string strContent = sr.ReadToEnd();
                    return strContent;// got error on this line
                }
            }
        }

1 个答案:

答案 0 :(得分:4)

返回string而不是List<string>

另一个纠正(但不是错误)将int更改为string,因为您获得了以下属性的字符串值:

public string no { get; set; }
public string poin { get; set; }
public string harga { get; set; }