我试图在C#中反序列化我的JSON文件,并出现以下错误:“ Newtonsoft.Json.dll中发生了'Newtonsoft.Json.JsonSerializationException类型的异常,但未在用户代码中处理”
我的JSON是:
[{"Yes":"52","No":"41"}]
Run Code Online (Sandbox Code Playgroud)
我的C#代码是
public class survey
{
public string Yes { get; set; }
public string No { get; set; }
}
protected void Button1_Click(object sender, EventArgs e)
{
using (StreamReader r = new StreamReader("sample.json"))
{
string json = r.ReadToEnd();
var items = JsonConvert.DeserializeObject<survey>(json);
var a = items.Yes;
TextBox1.Text = a;
}
}
Run Code Online (Sandbox Code Playgroud)
谁能帮帮我吗。
它应该是
JsonConvert.DeserializeObject<List<Survey>>(jsonstr);
Run Code Online (Sandbox Code Playgroud)
代替
JsonConvert.DeserializeObject<survey>(json);
Run Code Online (Sandbox Code Playgroud)
因为您要以[是,否]数组形式获取JSON
然后您将获得如下数据
var a = items[0].Yes;
Run Code Online (Sandbox Code Playgroud)
编辑
完整的代码可能如下所示
string jsonstr = File.ReadAllText("some.txt");
var items = JsonConvert.DeserializeObject<List<Survey>>(jsonstr);
var a = items[0].Yes;
Run Code Online (Sandbox Code Playgroud)
这个班级看起来像这样
public class Survey
{
[JsonProperty("Yes")]
public string Yes { get; set; }
[JsonProperty("No")]
public string No { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1391 次 |
最近记录: |