首页 > 解决方案 > C# json 自定义序列化

问题描述

我在 c# 中创建了一个自定义标签对象,我需要从这个对象创建 json 对象。但是我已经将标签从“标签”控件派生到自定义标签对象。序列化自定义标签对象后,json 被标签属性填充。但是,我不需要它。我只需要传递自定义标签对象。

这是自定义标签:

public class customLabel:Label
{

        public string X { get; set; }

        public string Y { get; set; }

        public string H { get; set; }

        public string W { get; set; }

        public string FontName { get; set; }

        public string FontSize { get; set; }

        public string Type { get; set; }

        public string Align { get; set; }

        public string _Text { get; set; }


}

我正在使用 Newtonsoft.Json json 序列化

标签: c#json

解决方案


创建包含所需属性的自定义。JsonConvertor

然后将其传递给以SerializeObject控制序列化。

string result = JsonConvert.SerializeObject(
                     customLabel,
                     Formatting.Indented,
                     new CustomLabelConverter(typeof(CustomLabel)));

推荐阅读