Jor*_*nes -1 .net c# serialization json deserialization
所以我正在通过这个例子来试图第一次尝试desialize https://www.newtonsoft.com/json/help/html/DeserializeObject.htm 我试图用json数据创建对象然后得到相应的属性.
好吧..我说错了
Newtonsoft.Json.JsonSerializationException:'无法将当前JSON数组(例如[1,2,3])反序列化为类型'json_deserializing.OppedAccounts',因为该类型需要一个JSON对象(例如{"name":"value"})来正确反序列化.要修复此错误,请将JSON更改为JSON对象(例如{"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如ICollection,IList),例如List从JSON数组反序列化.JsonArrayAttribute也可以添加到类型中以强制它从JSON数组反序列化.路径'',第1行,第1位.'
我是json和反序列化的新手,所以我不确定这里发生了什么.我的问题是,如何以propper方式反序列化json?我读了一些关于列表和东西的东西,但我无法连接点.
[
{
"uuid": "98e99e7a-df48-4b8b-adc9-e65c32410247",
"name": "UsernameOne",
"level": 4,
"bypassesPlayerLimit": false
},
{
"uuid": "b87e1cbc-c67c-4026-a359-8652ad9de8b4",
"name": "UsernameTwo",
"level": 4,
"bypassesPlayerLimit": false
}
]
Run Code Online (Sandbox Code Playgroud)
CSharp代码
public partial class MainWindow : Window
{
public string line = null;
public MainWindow()
{
InitializeComponent();
Deserialize();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if(line != null)
{
OppedAccounts account = JsonConvert.DeserializeObject<OppedAccounts>(line);
Debug.Print(account.name);
}
}
private void Deserialize()
{
using (StreamReader sr = new StreamReader("ops.json"))
{
line = sr.ReadToEnd();
}
tbjson.AppendText(line);
}
}
Run Code Online (Sandbox Code Playgroud)
和班级
class OppedAccounts
{
public string uuid { get; set; }
public string name { get; set; }
public int level { get; set; }
public bool bypassplayerlimit { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
您正在反序列化数组,因此您期望返回一个对象数组.更改to 的类型account和泛型参数.JsonConvert.DeserializeObjectList<OppedAccounts>
List<OppedAccounts> accounts = JsonConvert.DeserializeObject<List<OppedAccounts>>(line);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |