我有这堂课
namespace Watermark
{
public class Template
{
int Width { get; set; } = 700;
int Height { get; set; } = 700;
Picture Picture { get; set; }
List<Shape> Shape { get; set; }
List<Word> Word { get; set; }
}
public class Picture
{
int X { get; set; }
int Y { get; set; }
}
public class Shape
{
List<PointF> Point { get; set; }
string Color { get; set; }
}
public class Word
{
string Text { get; set; }
int Width { get; set; }
HorizontalAlignment Alignment { get; set; } = HorizontalAlignment.Center;
string Color { get; set; }
string FontFamily { get; set; }
int Size { get; set; }
FontStyle Style { get; set; } = FontStyle.Regular;
}
}
我有这个JSON文件
{
"folderPath": "D:\\bfi",
"folderName": "ORI",
"Template": {
"Width": "700",
"Height": "700",
"Picture": {
"X": "270",
"Y": "0"
},
"Shape": [
{
"Point": [
{
"X": 35,
"Y": 0
},
{
"X": 260,
"Y": 0
},
{
"X": 260,
"Y": 250
},
{
"X": 147.5,
"Y": 310
},
{
"X": 35,
"Y": 250
},
{
"X": 35,
"Y": 0
}
],
"Color": "13293D"
},
{
"Point": [
{
"X": 0,
"Y": 555
},
{
"X": 700,
"Y": 555
},
{
"X": 700,
"Y": 700
},
{
"X": 0,
"Y": 700
},
{
"X": 35,
"Y": 250
},
{
"X": 0,
"Y": 555
}
],
"Color": "13293D"
}
],
"Word": [
{
"Text": "TEST",
"Width": 205,
"Alignment": "Center",
"Color": "FAA916",
"FontFamily": "Arial",
"Size": 40,
"Style": "Regular"
}
]
}
}
我尝试将JSON文件映射到我的班级
var jsonString = File.ReadAllText("appsettings.json");
var jsonModel = JsonSerializer.Deserialize<Template>(jsonString);
但是所有复杂对象都显示为空,我在做什么错了?
答案 0 :(得分:2)
您在这里有两个问题:
您在根级别上缺少一个类。您需要添加此类:
public class RootObject
{
public string FolderPath { get; set; }
public string FolderName { get; set; }
public Template Template { get; set; }
}
反序列化而不是Template
:
var jsonModel = JsonSerializer.Deserialize<RootObject>(jsonString);
如果您同时执行上述两项操作,则JSON将反序列化属性。