.NET|--格式转换|--实体转换为yaml格式字符串( 忽略属性,双引号 )

前言

安装依赖的包"YamlDotNet"

Install-Package YamlDotNet

由json格式转换为yaml格式

using YamlDotNet.Core;
using YamlDotNet.Serialization;

namespace ConsoleApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person("张三", 30, "北京");

            // 使用YamlDotNet进行转换
            var serializer = new SerializerBuilder().Build();
            string yamlString = serializer.Serialize(person);

            // 打印转换后的YAML字符串
            Console.WriteLine(yamlString);
            /*
//输出
Name: '张三'
Age: 30
City: 北京
DoubleQuotedProperty: ""
             */
        }

        internal struct Person
        {
            public Person(string name, int age, string city)
            {
                Name = name;
                Age = age;
                City = city;
            }

            [YamlMember(ScalarStyle = ScalarStyle.SingleQuoted)]
            public string Name { get; set; }
            public int Age { get; set; }
            public string City { get; set; }

            /// <summary>
            /// 忽略输入和输出的字段
            /// </summary>
            [YamlIgnore]
            public string IgnoreProperty { get; set; }

            /// <summary>
            /// 加双引号
            /// </summary>
            [YamlMember(ScalarStyle = ScalarStyle.DoubleQuoted)]
            public string DoubleQuotedProperty { get; set; }


        }
    }
}
posted @ 2023-05-29 09:45  zh89233  阅读(41)  评论(0编辑  收藏  举报