JSON不会映射到复杂的类和集合

时间:2019-11-02 15:11:47

标签: c# json

我有这堂课

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);

但是所有复杂对象都显示为空,我在做什么错了?

enter image description here

1 个答案:

答案 0 :(得分:2)

您在这里有两个问题:

  1. 您的属性不是公开的,正如@dbc在评论中指出的
  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将反序列化属性。

提琴:https://dotnetfiddle.net/DAEN7G