.net 如何将YAML转换为JSON?[关闭]

8ljdwjyq  于 2023-06-07  发布在  .NET
关注(0)|答案(3)|浏览(681)

**已关闭。**此问题不符合Stack Overflow guidelines。目前不接受答复。

这个问题似乎不是关于在help center定义的范围内编程。
5天前关闭。
截至5天前,社区正在审查是否重新开放此问题。
Improve this question
我希望在YAML文件和JSON之间进行转换。这真的很难找到任何信息。

6ie5vjzr

6ie5vjzr1#

如果你不需要Json.NET的特性,你也可以直接使用Serializer类来发出JSON:

// now convert the object to JSON. Simple!
var js = new Serializer(SerializationOptions.JsonCompatible);

var w = new StringWriter();
js.Serialize(w, o);
string jsonText = w.ToString();

你可以在这里检查两个工作小提琴:

3yhwsihp

3yhwsihp2#

通过使用内置的JSON库沿着YamlDotNet可以做到这一点。这在YamlDotNet文档中并不明显,但我找到了一种相当简单的方法。

// convert string/file to YAML object
var r = new StreamReader(filename); 
var deserializer = new Deserializer(namingConvention: new CamelCaseNamingConvention());
var yamlObject = deserializer.Deserialize(r);

// now convert the object to JSON. Simple!
Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer();

var w = new StringWriter();
js.Serialize(w, yamlObject);
string jsonText = w.ToString();

我很惊讶这工作以及它!JSON输出与其他基于Web的工具相同。

inb24sb2

inb24sb23#

下面是使用YamlDotNet.Serialization的完整代码示例。这些示例是将对象转换为YAML字符串和将YAML字符串转换为对象。然后可以在. NET中轻松地序列化和反序列化(封送和反封送)JSON。
使用内置System.Text.Json的示例:
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/how-to?pivots=dotnet-7-0#serialization-example
如果你想在.NET运行时中为YAML提供一个基本的序列化器,你可以在这里投票:
https://github.com/dotnet/runtime/issues/83313
然而,正如ASP.NET团队的@davidfowl所指出的:
https://www.nuget.org/packages/YamlDotNet是.NET的实际YAML实现
https://github.com/dotnet/runtime/issues/83313#issuecomment-1467411353

using System;
using System.Collections.Generic;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public float HeightInInches { get; set; }
    public Dictionary<string, Address> Addresses { get; set; }

}
   
public class Program
{
    public static void Main()
    {
        var person = new Person
        {
            Name = "Abe Lincoln",
            Age = 25,
            HeightInInches = 6f + 4f / 12f,
            Addresses = new Dictionary<string, Address>{
                { "home", new  Address() {
                        Street = "2720  Sundown Lane",
                        City = "Kentucketsville",
                        State = "Calousiyorkida",
                        Zip = "99978",
                    }},
                { "work", new  Address() {
                        Street = "1600 Pennsylvania Avenue NW",
                        City = "Washington",
                        State = "District of Columbia",
                        Zip = "20500",
                    }},
            }
        };

        var serializer = new SerializerBuilder()
            .WithNamingConvention(CamelCaseNamingConvention.Instance)
            .Build();
        var yaml = serializer.Serialize(person);
        System.Console.WriteLine(yaml);
        // Output: 
        // name: Abe Lincoln
        // age: 25
        // heightInInches: 6.3333334922790527
        // addresses:
        //   home:
        //     street: 2720  Sundown Lane
        //     city: Kentucketsville
        //     state: Calousiyorkida
        //     zip: 99978
        //   work:
        //     street: 1600 Pennsylvania Avenue NW
        //     city: Washington
        //     state: District of Columbia
        //     zip: 20500

        var yml = @"
name: George Washington
age: 89
height_in_inches: 5.75
addresses:
  home:
    street: 400 Mockingbird Lane
    city: Louaryland
    state: Hawidaho
    zip: 99970
";

        var deserializer = new DeserializerBuilder()
            .WithNamingConvention(UnderscoredNamingConvention.Instance)
            .Build();

        //yaml contains a string containing your YAML
        var p = deserializer.Deserialize<Person>(yml);
        var h = p.Addresses["home"];
        System.Console.WriteLine($"{p.Name} is {p.Age} years old and lives at {h.Street} in {h.City}, {h.State}.");
        // Output:
        // George Washington is 89 years old and lives at 400 Mockingbird Lane in Louaryland, Hawidaho.

    }
}

来源:
https://dotnetfiddle.net/CQ7ZKi
https://github.com/aaubry/YamlDotNet

相关问题