0

I'm trying to use Json.net on a WPF application. I obtain a string, from a webserver i connect, that looks something like this.

[{"id":"11","title":"Default","nclient":"3"},{"id":"18","title":"GrupoPorreiro","nclient":"0"}]

and the code im using to deserialize it is this.

public void preencheCampos()
    {
        try
        {

            HttpWebRequest request =
            (HttpWebRequest)WebRequest.Create("URL");
            //request.Method = "POST";
            request.ContentType = "application/json";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11";
            request.CookieContainer = ApplicationState.GetValue<CookieContainer>("cookie");

            WebResponse response = request.GetResponse();
            Stream data = response.GetResponseStream();
            String html = String.Empty;
            request.CookieContainer = ApplicationState.GetValue<CookieContainer>("cookie");

            using (StreamReader sr = new StreamReader(data))
            {
                html = sr.ReadToEnd();
            }


            StringBuilder sb = new StringBuilder();
            List<string> entities = (List<string>)JsonConvert.DeserializeObject(html, typeof(List<string>));
            foreach (string items in entities)
            {
                sb.Append(items);
            }

         //...

        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message);
        }
    }

but when it gets to the JsonConvert.DeserializeObject part i get an exception that says:

"Error reading string. Unexpected token: StartObject. Path'[0]', line 1, position 2."

4

1 回答 1

4

我根据需要为一个类写了一些快速代码。这适用于您发布的 JSON 字符串。就像您在评论中提到的那样,我为该对象创建了一个类并将其用作我的列表项。

static void Main(string[] args)
{
    string html = "[{\"id\":\"11\",\"title\":\"Default\",\"nclient\":\"3\"},{\"id\":\"18\",\"title\":\"GrupoPorreiro\",\"nclient\":\"0\"}]";

    List<item> entities = (List<item>)JsonConvert.DeserializeObject(html, typeof(List<item>));

}

class item
{
    public string id;
    public string title;
    public string nclient;
}
于 2013-01-23T15:34:42.923 回答