编写类以反序列化JSON文件时遇到问题。
我的课程如下:
public class Button1
{
public string Caption = "";
public Dictionary<string, Button1> Buttons;
}
public class ButtonsMenu
{
public Dictionary<string, Button1> Buttons;
}
我试图反序列化这个JSON:
{
"Buttons": {
"Activity": {
"btn1": {
"Caption": "Promeni sostojba"
},
"btn2": {
"Caption": "Izvrsi nesto drugo"
}
},
"Navigate": {
"btnA": {
"Caption": "Pojdi na druga forma"
},
"btnB": {
"Caption": "Otvori nesto razlicno"
}
},
"Print": {
"btnX1": {
"Caption": "Pecati nalog"
},
"btnX2": {
"Caption": "Pecati report"
}
}
}
}
使用Json.Net这样:
var buttonDef = JsonConvert.DeserializeObject<ESB.Shared.DTO.ButtonsMenu>(formDefJson);
我的问题是当我尝试反序列化我的JSON时,我有三个项目Activity
,Navigate
和Print
,但字段Captions
到处都是空的。
你能告诉我课上缺少什么吗?
答案 0 :(得分:0)
使用班级
public class Btn1
{
public string Caption { get; set; }
}
public class Btn2
{
public string Caption { get; set; }
}
public class Activity
{
public Btn1 btn1 { get; set; }
public Btn2 btn2 { get; set; }
}
public class BtnA
{
public string Caption { get; set; }
}
public class BtnB
{
public string Caption { get; set; }
}
public class Navigate
{
public BtnA btnA { get; set; }
public BtnB btnB { get; set; }
}
public class BtnX1
{
public string Caption { get; set; }
}
public class BtnX2
{
public string Caption { get; set; }
}
public class Print
{
public BtnX1 btnX1 { get; set; }
public BtnX2 btnX2 { get; set; }
}
public class Buttons
{
public Activity Activity { get; set; }
public Navigate Navigate { get; set; }
public Print Print { get; set; }
}
public class RootObject
{
public Buttons Buttons { get; set; }
}
或使用服务生成类http://json2csharp.com/ 希望我帮助你:)
更新:如果您想使用字典试试这个
public class Button1
{
public string Caption;
public Dictionary<string, Dictionary<string, Button1>> Buttons;
}
public class ButtonsMenu
{
public Dictionary<string, Dictionary<string, Button1>> Buttons;
}
答案 1 :(得分:0)
它不起作用,因为你的JSON并不完全匹配你的类结构。有两种方法可以解决它 - 更改类或更改JSON。
如果您希望更改JSON以使其适用于您现有的类,那么您需要一个额外的Buttons
级别围绕内部按钮对象,如下所示:
{
"Buttons": {
"Activity": {
"Buttons": {
"btn1": {
"Caption": "Promeni sostojba"
},
"btn2": {
"Caption": "Izvrsi nesto drugo"
}
}
},
"Navigate": {
"Buttons": {
"btnA": {
"Caption": "Pojdi na druga forma"
},
"btnB": {
"Caption": "Otvori nesto razlicno"
}
}
},
"Print": {
"Buttons": {
"btnX1": {
"Caption": "Pecati nalog"
},
"btnX2": {
"Caption": "Pecati report"
}
}
}
}
}
小提琴:https://dotnetfiddle.net/vAWhUd
如果您希望更改类以适合您的问题中的JSON,那么您需要将外部Buttons
字典更改为嵌套字典:
public class ButtonsMenu
{
public Dictionary<string, Dictionary<string, Button1>> Buttons;
}
public class Button1
{
public string Caption = "";
}