wpf 使用 JsonConvert.DeserializeObject 时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14483107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error using JsonConvert.DeserializeObject
提问by Thought
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.
我正在尝试在 WPF 应用程序上使用 Json.net。我从我连接的网络服务器获得一个字符串,看起来像这样。
[{"id":"11","title":"Default","nclient":"3"},{"id":"18","title":"GrupoPorreiro","nclient":"0"}]
[{"id":"11","title":"默认","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:
但是当它到达 JsonConvert.DeserializeObject 部分时,我得到一个异常,说:
"Error reading string. Unexpected token: StartObject. Path'[0]', line 1, position 2."
“读取字符串时出错。意外标记:StartObject。路径'[0]',第 1 行,位置 2。”
回答by ryadavilli
I wrote out some quick code for a class as you need. This works with the JSON string you have posted. Like you mentioned in your comment I have created a class for the object and used it as my List Item.
我根据您的需要为类编写了一些快速代码。这适用于您发布的 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;
}

