Giter VIP home page Giter VIP logo

yamldotnet's Introduction

YamlDotNet

Appveyor NuGet
Build status NuGet

YamlDotNet is a YAML library for netstandard and other .NET runtimes.

YamlDotNet provides low level parsing and emitting of YAML as well as a high level object model similar to XmlDocument. A serialization library is also included that allows to read and write objects from and to YAML streams.

YamlDotNet's conformance with YAML specifications:

YAML Spec YDN Parser YDN Emitter
v1.1
v1.2

What is YAML?

YAML, which stands for "YAML Ain't Markup Language", is described as "a human friendly data serialization standard for all programming languages". Like XML, it allows to represent about any kind of data in a portable, platform-independent format. Unlike XML, it is "human friendly", which means that it is easy for a human to read or produce a valid YAML document.

The YamlDotNet library

The library has now been successfully used in multiple projects and is considered fairly stable. It is compatible with the following runtimes:

  • netstandard 2.0
  • netstandard 2.1
  • .NET 6.0
  • .NET 7.0
  • .NET Framework 4.7

Quick start

Here are some quick samples to get you started which can be viewed in this fiddle.

Serialization from an object to a string

using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
...

 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

Deserialization from a string to an object

using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
...

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)  // see height_in_inches in sample yml 
    .Build();

//yml 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.

More information

More information can be found in the project's wiki.

Installing

Just install the YamlDotNet NuGet package:

PM> Install-Package YamlDotNet

If you do not want to use NuGet, you can download binaries here.

YamlDotNet is also available on the Unity Asset Store.

Contributing

Please read CONTRIBUTING.md for guidelines.

Release notes

Please see the Releases at https://github.com/aaubry/YamlDotNet/releases

Sponsorships

A big shout out to all of our sponsors

AWS

yamldotnet's People

Contributors

aaubry avatar am11 avatar antoine-aubry avatar atruskie avatar conniey avatar dol-leodagan avatar dschroer avatar edwardcooke avatar gjdonkers avatar hemnstill avatar jeffman avatar jj11teen avatar lahma avatar laxis96 avatar leon-m avatar mattmiller85 avatar meziantou avatar mlaily avatar nbarbettini avatar pandateen avatar pensono avatar premun avatar prochnowc avatar rudolfolah avatar rutger-dijkstra-kpn avatar steinbitglis avatar stijnherreman avatar sungam3r avatar tymokvo avatar vwxyzh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yamldotnet's Issues

string numbers should be quoted

You get the same result if you serialize 5 or "5" or 5.0. As a result, type information is lost:

var sw = new StringWriter();
(new Serializer()).Serialize(sw, "5");
(new Serializer()).Serialize(sw, 5);
(new Serializer()).Serialize(sw, 5.0);
sw.ToString().Dump("result"); // output: "5\n...\n5\n...\n5\n..."

Since the result can be explicitly deserialized into int, string, or double it's not a serious bug.

I'm not even sure what the yaml spec says on the issue, as I usually just see what the PyYaml implementation does:

>>> import yaml
>>> yaml.dump(1)
'1\n...\n'
>>> yaml.dump(1.0)
'1.0\n...\n'
>>> yaml.dump('1')
"'1'\n"

Anyway, great work on the library so far, the last release fixed a bug I was having trouble with :)

Serializer doesn't emit a tag with type

Hi,
Not sure I'm using the library correctly, but when trying to serialize a simple class like this:

namespace TestYamlDotNet
{
    public class Fruit
    {
        public string Name { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var serializer = new Serializer(SerializationOptions.Roundtrip);
            var orange = new Fruit() { Name = "Orange" };
            serializer.Serialize(Console.Out, orange);
        }
    }

It is outputing only the Name: Orange property instead of outputing something like:

!TestYamlDotNet.Fruit
Name: Orange

Is this a correct behavior? I don't see how I can deserialize a node that doesn't output any tag information.

Unit test failure: RoundtripExample7

roji@patroklos:~/work/YamlDotNet/YamlDotNet.UnitTests/bin/Debug$ /usr/local/xunit-1.9.1/xunit.console.exe YamlDotNet.UnitTests.dll
xUnit.net console test runner (64-bit .NET 2.0.50727.1433)
Copyright (C) 2007-11 Microsoft Corporation.

xunit.dll: Version 1.9.0.1566
Test assembly: /home/EAGLERD/roji/work/YamlDotNet/YamlDotNet.UnitTests/bin/Debug/YamlDotNet.UnitTests.dll

YamlDotNet.UnitTests.RepresentationModel.YamlStreamTests.RoundtripExample7 [FAIL]
Assert.Equal() Failure
Position: First difference is at position 16
Expected: a literal scalar
Actual: a literal scalar
Stack Trace:
at YamlDotNet.UnitTests.RepresentationModel.YamlStreamTests.RoundtripTest (System.String yamlFileName) [0x00000] in :0
at YamlDotNet.UnitTests.RepresentationModel.YamlStreamTests.RoundtripExample7 () [0x00000] in :0
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in :0

95 total, 1 failed, 0 skipped, took 0.431 seconds

Auto-ignore properties with no setter

It's annoying to have to mark all my computed properties with [YamlIgnore]. I suppose some people might want to serialize those properties (say, for reporting purposes), but it makes deserialization impossible! Can we have an option to auto-ignore properties with no setter? (Not properties with a private setter, just ones with no setter at all.) Either that or just don't crash when trying to deserialize a property with no setter (just fail silently).

object array not serialized.

If I try to serialize an object array like so:

var s = new Serializer();
var tw = new StringWriter();
s.Serialize(tw, new { Name="test", Item=new object[] { 1, 2, "3"} } );
var output = tw.ToString()

I get output like this:

Name: test
Item: 
- {}
- {}
- {}

It seems that it does not properly get the boxed values from the object array.

Deserialization: no way to specify general key to property mapping

Deserialization would be easier if we could define and use general key to property mapping rules.
Basically like INamingConvention but in reverse way.

For example deserializing:

person:
    full name: Bob
    age: 15
    eats open-mouthed: yes

into

class Person
{
    public string FullName { get; set; }
    public int Age { get; set; }
    public bool EatsOpenMouthed { get; set; }
}

would be much easier if we could define and use general mapping like:

Key -> PascalCase

Currently one must FOR ALL properties either:

  1. use [YamlAlias]
  2. hardcode property name and use it in INamingConvention

Non-decimal integer bases are not supported

I have a simple class with one int property:

class TestClass
{
    public int TestField { get; set; }
}

I try to deserialize the following YAML file:

TestField: 0x10

...using the following code:

var str = new StringReader("TestField: 0x10");
var d = new Deserializer();
var obj = d.Deserialize<TestClass>(str);

I would expect obj.TestField to have a value of 16. However, an exception is thrown during deserialization, when trying to parse "0x10" in ScalarNodeDeserializer.cs:

case TypeCode.Int32:
    value = Int32.Parse(scalar.Value, numberFormat);
    break;

It seems that the possibility of having a non-decimal base is being ignored. Many integer bases (binary, octal, hexadecimal and sexagesimal) should be allowed per the YAML spec. For reference, this works as expected in pyyaml:

>>> import yaml
>>> print yaml.load("test: 0x10")
{'test': 16}

IYamlTypeConverter and FullObjectGraphTraversalStrategy do not seem to work well together

Hi,

I'm currently trying to create a custom type converter for my code. In particular I'm trying to serialize and deseralize FileInfo and DirectoryInfo types. Serializing these types is just a convenience - we are working around needing to serialize them at all with proxy properties.

But, after registering my attempt at a custom converter, I still get the same exception as I did without registering the converter.

The root cause, is that the FileInfo type has an infinite/recursive object graph - triggering the traversal exception. Debugging the problem, I found that the FullObjectGraphTraversalStrategy class does not take into consideration the custom converters... and traverses down the type anyway.

I think, the correct behaviour should be more like: if the current type is handled by a custom converter, it should be treated as a ?scalar? and the object graph should not be traversed down further for that node.

I'd be happy to help patch/add this behaviour (if you desire) but I need a few hints... I'm not quite sure where I should put this custom converter check (or what the resulting type should be).

Btw, this is a fantastic project, I appreciate the hard work of all the contributors!

Cannot use library from signed assembly

We can either sign the YamlDotNet.dll, or provide some kind of instructions for a workaround. As of now, anyone trying to use this assembly from a signed assembly is going to get the error:
Referenced assembly 'YamlDotNet' does not have a strong name
and there's no documentation on how to workaround that. Ideally we can just fix it.

Support the .NET DefaultValue attribute

YamlDotNet does not emit properties that have default values - null, 0, etc.

It would be really nice to have YamlDotNet pick up the standard DefaultValue attribute, which would allow users to specify any value as a default (and therefore not serialized).

I'll get to work on this when I have some spare time...

Serializer doesn't handle tag mappings

Somewhat related to issue #49, the Serializer class doesn't handle tag mappings unlike Deserializer that can handle it. This is an unbalanced feature that is making impossible to output a type with a different tag (for example, we want to remove some namespaces for some known applications).

If you give me some hint where you would introduce it - I imagine in a chained IObjectGraphVisitor - but I'm not sure, I could try to add this feature.

No RepresentationModel version 1.1.16 nuget package

RepresentationModel version 1.1.15 references Core version 1.1.15 but when installing via Install-Package YamlDotNet.RepresentationModel, Core 1.1.16 gets installed.

This ends up throwing a FileNotFoundException with the message, "Could not load file or assembly 'YamlDotNet.Core...."

A workaround right now is to do:

Install-Package YamlDotNet.Core -Version 1.1.15
Install-Package YamlDotNet.RepresentationModel -IgnoreDependencies

Cryptic exception in case of duplicated keys

Key1: 0
Key1: 0
(Lin: 0, Col: 0, Chr: 0) - (Lin: 0, Col: 0, Chr: 0): Error while deserializing node [Mapping start [anchor = , tag = , isImplicit = True, style = Block]]

It's completely unclear that the problem is the key duplicating. We've just wasted 30 minutes to find why our 200-lines yaml was not parsed after git merge.

Type information lost when assigning to generic dictionaries

If I store an associative array with values of mixed types, e.g.:

var properties = new Dictionary<string, object>
{
    { "Name", "One" },
    { "Number", 1 },
    { "Double", 3.14 }
}
...
serializer.Serialize(writer, properties);

When I retrieve such a structure, the type information for both "Number" and "Double" are lost; instead, they are returned as strings.

var properties = deserializer.Deserialize<Dictionary<string, object>>(reader);

However, as the standard indicates that numbers stored as strings should be delineated with double quotes and otherwise treated as numbers, the deserializer should probably try to cast the value appropriately before populating the dictionary.

Derived classes serialization with YamlDotNet.UnitTests.RepresentationModel

I am facing the following serialization requirement: using the representation model, serialize a List<AbstractBaseClass>. Serialization should manage the different derived classes on runtime.

I wrote a test case to exemplify it.
Please see: http://pastebin.com/gTfAx80G

I am thinking that a solution like adding YamlInclude attribute would get it working in the same way as XML de/serializers uses XmlInclude, and probably a good chance to use YAML tags in action.

What do you think?

Thanks for work great work on YamlDotNet Antonie. Keep pushing!

Deserialize multiple documents contained in single file

Hi Antoine,

is there a way to deserialize multiple documents into sequence/collection of user defined types?
I've tried following:

  • declared a class
public class Person
{
    public string Name { get; set; }
}
  • then opened file containing few documents

---
Name: Andy

---
Name:  Brad
...
  • then tried to deserialize it
var serializer = new YamlSerializer<List<Person>>(streamReader);

// it fails here
List<Person> friends = serializer.Deserialize();

YamlDotNetEditor not showing up...

I just tried to install YamlDotNetEditor extension in VS2012, I do not receive any error and I see it listed among the installed extensions, but then nothing happens. I'd expect to see it listed among the available editor options in Tools > Options > Text Editor > File Extensions, but I don't. How am I supposed to add it? I added a .raml file to my project and I'd like to edit it with YamlDotNetEditor. Also, I tried to add a basic .yaml file but the editor does not kick in.

Thanks

Exception scanning block scalar with leading tabs

According to the yaml spec, literal style block scalars should be able to contain tabs. When trying to parse a yaml document with a format like this:

output: |
  \tline beggining with tab
  another line

Where the '\t' is a tab (preceded by a valid indentation of two spaces).

Currently, I get the following error when loading a yaml stream with a block scalar as above:
"While scanning a block scalar, find a tab character where an intendation space is expected."

I don't think it should be expecting an indentation space at this point.

Option for indenting behavior (mapping of sequence)

The library does not seem to indent a mapped sequence by default like this:

Key:
- item1
- item2
- item3

Often the alternative can improve readability or at the very least look much nicer

Key:
  - item1
  - item2
  - item3

I'd suggest an option for either the Emiter/Serializer or each mapping to change this behavior.

If this functionality already exists, my apology I was not able to find anything related in the API.

exception with nested serialization

If I serialize an object, stick that object in another object (as a string attribute), then serialize that. The container object deserializes fine, but the "payload" object throws a SyntaxErrorException. It looks like newlines are being lost along the way:

An example LINQPad is below. A newline is lost when the container is deserialized.

Note that the exception only happens when EmitDefaults is set, but I beiieve that this is because without the default, there is only one "root" element in the payload and there are no newlines to drop.

void Main()
{
//    var s = new Serializer();
    var s = new Serializer(SerializationOptions.EmitDefaults);
    var ds = new Deserializer();

    // serialize AMessage
    var tw = new StringWriter();
    s.Serialize(tw, new AMessage(){ Payload = new PayloadA(){X=5,Y=6}});
    tw.ToString().Dump();

    // stick serialized AMessage in envelope and serialize it
    var e = new Env(){Type = "some-type", Payload = tw.ToString()};

    tw = new StringWriter();
    s.Serialize(tw, e);
    tw.ToString().Dump("env");

    // deserialize envelope
    var e2 = ds.Deserialize<Env>(new StringReader(tw.ToString())).Dump("denv");

    // deserialize payload - fails if EmitDefaults is set
    ds.Deserialize<AMessage>(new StringReader(e2.Payload)).Dump();
}

// Define other methods and classes here

class Env
{
    public string Type { get; set; }
    public string Payload { get; set; }
}

class Message<TPayload>
{
    public int id { get; set; }
    public TPayload Payload { get; set; }
}

class PayloadA
{
    public int X { get; set; }
    public int Y { get; set; }
}

class AMessage : Message<PayloadA>{}

Serializing a dynamic type with a naming convention

I'm trying to serialize a dynamic (specifically an ExpandoObject) while using a naming convention. The names of the properties aren't getting run through the Apply method of the INamingConvention but otherwise is serializing correctly. Is this something that I could accomplish?

Simplify YamlDotNet assembly names?

This is not a huge issue, what do you think of renaming assembly names to?

  • From YamlDotNet.Core to YamlDotNet
  • From YamlDotNet.RepresentationModel to YamlDotNet.Serialization

I believe that It will be clearer when using YamlDotNet for a end-user.

From a pure end-user perspective, I'm also not sure about separating YamlDotNet and the Serialization, while in terms of concepts it is relevant, in terms of end user, I found it quite overkill. Most of the consumers of YamlDotNet will use the serialization part of YamlNotNet. Having a single library for handling YAML is more appealing to me.

TypeResolvers

Hi,

I am using YamlDotNet to read my yaml files and it works excellent,
but it would be great if I could convert YamlNodes into .Net types such as int, float, string , List or Dictionary.

I can see that you have implemented TypeResolvers wich have method Resolve.
Do you have plans to continue with work on this method so that it could return .Net types?
Have you any suggestions that could help me?

Best regards,
Vladimir

Non-specific node tag problem

I have some Ruby generated YAML files, which uses non-specific node tags (chapter 8.2 for YAML 1.1 specification, chapter 6.9.1 for YAML 1.2 specification). It's single exclamation mark before node, which purpose is to force basic interpretation (differently specified for 1.1 and 1.2 standards) of node value.

Unfortunately such non-specific node tags causes YamlDotNet.Core.SyntaxErrorException

yamldotnet-non-specific-tag-problem

The issue can be reproduced with YAML code snippet from YAML specification.

Best regards
Rik

add a possibility to define the order of properties for serialization

Using YamlDotNet in a WPF application with xaml databinding to an instance serialized/deserialized to/from yaml, I noticed that the order of the properties for serialization depends on the order of the controls bound to the correspondent property in the view.

The shape of the view affects the shape of the data. That’s weird.

I think this is because YamlDotNet uses reflection. (And xaml databinding uses reflection?) Reflection is caching its results and does not guarantee for the ordering. („The GetProperties method does not return properties in a particular order, such as alphabetical or declaration order.“).

I wrote a unit test to reproduce this behaviour and its effect on serialization:

 public class A
{
    // todo: maybe introduce [YamlOrder(0)]
    public int P1 { get; set; }

    // todo: maybe introduce [YamlOrder(1)]
    public int P2 { get; set; }
}

[Fact]
public void SerializeTwice_CacheOfReflectionIsFilledDifferent_ResultIsSameForEachRun()
{
    var c = new A() { P1 = 1, P2 = 2 };

    var s = new Serializer();
    var b1 = new StringWriter();
    var b2 = new StringWriter();

    typeof(A).GetProperty("P2");  // get second property by Reflection

    s.Serialize(b1, c);

    GC.Collect();       
    GC.WaitForPendingFinalizers();

    typeof(A).GetProperty("P1");  // get first property by Reflection

    s.Serialize(b2, c);            

    var r1 = b1.ToString();
    var r2 = b2.ToString();

    Assert.Equal(r1, r2); // test fails with current YamlDotNet
} 

Question about generic serialization

Here's a contrived example to demonstrate my question:

Say I have some messages defind by their payloads, and a generic envelope
that I stick a payload in and send/receive with. This is generally how I would
structure that classes:

class RequestMessage
{
    [YamlAlias('request')]
    string Request { get; set }

    [YamlAlias('requester_name')]
    string RequesterName { get; set; }
}

class ConfigMessage
{
    [YamlAlias('a')]
    string SettingA { get; set; }

    [YamlAlias('b')]
    int SettingB { get; set; }
}


class MessageEnvelope<TPayload>
{
    [YamlAlias('message_type')]
    string Type { get; set; }

    [YamlAlias('payload')]
    TPayload Payload { get; set; }
}

One issue I've been trying to figure out is how do you make this work well
with serialization, or more accurrately deserialization. If I create and object
and serialize it like so:

var ys = new Serializer();
var sr = new StringWriter();

var msg = new MessageEnvelope<ConfigMessage>(){
        Type="config", 
        Payload = new ConfigMessage(){
            SettingA = "red",
            SettingB = 5
            }
        };

ys.Serialize(sr, msg);

sr.ToString().Dump();

Ideally it creates yaml documents that looks like:

---
message_type: request
payload:
    request: alpha
    requester_name: bob
...

---    
message_type: config
payload:
    a: red
    b: 5
...

Which it does now (I just tested, it use to just give 'payload: {}', but must
have been fixed in a recent update).

The question is, how do you deserialize this in one pass to an object, when you
don't know what the payload type is before deserializing?

Currently I'm treating the payload as a separate serialized object, which yields
yaml like this:

---
message_type: request
payload: 'request: alpha\nrequester_name: bob\n\n'
...

---
message_type: config
payload: 'a: red\nb: 5\n\n'
...

This isn't nearly as clean and readible, and I was hoping for a good way to
do this, does anyone have any ideas?

Throws System.Reflection.TargetException when serializing my object graph

Here's the stack trace - sorry I have no idea what in my object graph broke the serializer!

at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at YamlDotNet.RepresentationModel.Serialization.FullObjectGraphTraversalStrategy.TraverseGenericDictionary(Object value, Type type, Type dictionaryType, IObjectGraphVisitor visitor) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\FullObjectGraphTraversalStrategy.cs:line 154
at YamlDotNet.RepresentationModel.Serialization.FullObjectGraphTraversalStrategy.TraverseObject(Object value, Type type, IObjectGraphVisitor visitor, Int32 currentDepth) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\FullObjectGraphTraversalStrategy.cs:line 116
at YamlDotNet.RepresentationModel.Serialization.FullObjectGraphTraversalStrategy.Traverse(Object value, Type type, IObjectGraphVisitor visitor, Int32 currentDepth) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\FullObjectGraphTraversalStrategy.cs:line 94
at YamlDotNet.RepresentationModel.Serialization.FullObjectGraphTraversalStrategy.SerializeProperties(Object value, Type type, IObjectGraphVisitor visitor, Int32 currentDepth) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\FullObjectGraphTraversalStrategy.cs:line 197
at YamlDotNet.RepresentationModel.Serialization.FullObjectGraphTraversalStrategy.TraverseObject(Object value, Type type, IObjectGraphVisitor visitor, Int32 currentDepth) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\FullObjectGraphTraversalStrategy.cs:line 126
at YamlDotNet.RepresentationModel.Serialization.FullObjectGraphTraversalStrategy.Traverse(Object value, Type type, IObjectGraphVisitor visitor, Int32 currentDepth) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\FullObjectGraphTraversalStrategy.cs:line 94
at YamlDotNet.RepresentationModel.Serialization.FullObjectGraphTraversalStrategy.SerializeProperties(Object value, Type type, IObjectGraphVisitor visitor, Int32 currentDepth) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\FullObjectGraphTraversalStrategy.cs:line 197
at YamlDotNet.RepresentationModel.Serialization.FullObjectGraphTraversalStrategy.TraverseObject(Object value, Type type, IObjectGraphVisitor visitor, Int32 currentDepth) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\FullObjectGraphTraversalStrategy.cs:line 126
at YamlDotNet.RepresentationModel.Serialization.FullObjectGraphTraversalStrategy.Traverse(Object value, Type type, IObjectGraphVisitor visitor, Int32 currentDepth) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\FullObjectGraphTraversalStrategy.cs:line 94
at YamlDotNet.RepresentationModel.Serialization.FullObjectGraphTraversalStrategy.YamlDotNet.RepresentationModel.Serialization.IObjectGraphTraversalStrategy.Traverse(Object graph, Type type, IObjectGraphVisitor visitor) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\FullObjectGraphTraversalStrategy.cs:line 41
at YamlDotNet.RepresentationModel.Serialization.Serializer.CreateEmittingVisitor(Emitter emitter, IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, Object graph, Type type) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\Serializer.cs:line 178
at YamlDotNet.RepresentationModel.Serialization.Serializer.Serialize(Emitter emitter, Object graph, Type type) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\Serializer.cs:line 152
at YamlDotNet.RepresentationModel.Serialization.Serializer.Serialize(Emitter emitter, Object graph) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\Serializer.cs:line 130
at YamlDotNet.RepresentationModel.Serialization.Serializer.Serialize(TextWriter writer, Object graph) in d:\Work\YamlDotNet\YamlDotNet.RepresentationModel\Serialization\Serializer.cs:line 109
at FrEee.Game.Objects.Space.Galaxy.SerializeGameState(Stream stream) in c:\Users\Ed\Documents\Visual Studio 2012\Projects\FrEee\FrEee\Game\Objects\Space\Galaxy.cs:line 170
at FrEee.Game.Objects.Space.Galaxy.Save() in c:\Users\Ed\Documents\Visual Studio 2012\Projects\FrEee\FrEee\Game\Objects\Space\Galaxy.cs:line 234
at FrEee.Game.Objects.Space.Galaxy.SaveAll() in c:\Users\Ed\Documents\Visual Studio 2012\Projects\FrEee\FrEee\Game\Objects\Space\Galaxy.cs:line 247
at FrEee.Game.Objects.Space.Galaxy.Initialize(GameSetup gsu, Status status, Double desiredProgress) in c:\Users\Ed\Documents\Visual Studio 2012\Projects\FrEee\FrEee\Game\Objects\Space\Galaxy.cs:line 491
at FrEee.WinForms.Forms.MainMenuForm.<>c__DisplayClass4.<btnQuickStart_Click>b__2() in c:\Users\Ed\Documents\Visual Studio 2012\Projects\FrEee\FrEee.WinForms\Forms\MainMenuForm.cs:line 82

backreference "<<"

Hi, I (think) I do not get the backreference to work as I expect.

For simple referencing I get the substitution I expect :

btnSignIn: &signin1
how: css
what: "div.ScalableButtonRegular,#btnLogin"
btnSignin2: *signin1

=>

{ btnSignIn, { { how, css }, { what, div.ScalableButtonRegular,#btnLogin } } }, 
{ btnSignin2, { { how, css }, { what, div.ScalableButtonRegular,#btnLogin } } } ....

but using referencing like "backreference.yaml" does not substitute fully, "<<" is shown as a key-value.

  btnSignIn: &signin1
    how: css
    what: "div.ScalableButtonRegular,#btnLogin"
  btnSignin2:   
    <<: *signin1
    what: newWhatValue
{ btnSignIn, { { how, css }, { what, div.ScalableButtonRegular,#btnLogin } } }, 
{ btnSignin2, { { <<, { { how, css }, { what, div.ScalableButtonRegular,#btnLogin } } }, { what, newWhatValue } } }

and using your "backreference.yaml" also shows "<<" as a key value:

parent: 
  anchor: &default 
    key1: value1
    key2: value2
  alias: 
    <<: *default
    key2: Overriding key2
{[parent, { { anchor, { { key1, value1 }, { key2, value2 } } }, { alias, { { <<, { { key1, value1 }, { key2, value2 } } }, { key2, Overriding key2 } } } }]}    

I'd expect "alias" to show { alias, { { key1, value1 }, { key2, Overriding key2 } } }

or do I have to add logic to fix above?

Thanks

/Magnus

RepresentationModel.Serialization.Deserializer not compiled by project

I was playing with RepresentationModel.Serialization.Serializer and was expecting to have the Deserializer class work too. The file Deserializer.cs is included in the project, but its build action is set to None.

Apparently, this is work in progress... which has not progressed much lately. Any plans of having this code finished anytime soon?

Does YamlDotNet expose Yaml data type information in the API?

Does YamlDotNet have any API for determining the data type of a YamlScalarNode? I was just looking at the Wikipedia on Yaml data types and was hoping that this type information was available via the YamlDotNet API http://en.wikipedia.org/wiki/YAML#Data_types - Is it? Thanks.

-- Update - I see that when type is explicitly defined in the Yaml the YamlNode.Tag is set (e.g. tag:yaml.org,2020:float when yaml contains !!float 123). However, it is null when no explicit type information is present.

Question: Possible to work with comments?

Hi,

I am considering YamlDotNet for a Project and looked at the Samples, but I have a question: Is it possible to work with the comments of a yaml file? I.e. parse them into some kind of datatype when deserializing?

I want the basic workflow: Read in a YAML file, modify some data fields, and write out to another yaml file. The comments should be maintained (but not modified) in the process. Is this possible?

null values are removed from list

If you serialize a list of nullable objects, the objects set to null are removed from the list:

var obj = new string[] { "one", null, "three", null, "four" };
var tw = new StringWriter();
(new Serializer()).Serialize(tw, obj);
Console.WriteLine(tw.ToString());

returns

- one
- three
- four

Instead, it should use the "null" value from the yaml spec, section 10.2.1.1. Null

- one
- null
- three
- null
- four

Otherwise lengths and positions of array elements can be lost.

DynamicYaml capitalization problem

I've cloned repository, opened in VS.NET 2013 and fired up unit tests. One test "TestNonExistingMember" was failing with "YamlDotNet.Dynamic.DynamicYaml' to 'int?' since TryGetMember implementation inside returns DynamicYaml created from null YamlNode whenever member is not found.
Also for another test "TestMappingNode" the beginnig of MappingYaml I would change from:
private const string MappingYaml = @"---
receipt: Oz-Ware Purchase Invoice

into
private const string MappingYaml = @"---
Receipt: Oz-Ware Purchase Invoice

capitalizing receipt key then the test would also fail. This is also because decapitalized key search is done first and "empty" DynamicYaml is returned and capitalized search for Receipt is never actually done.

I discovered this when I was using YamlDotNet.Dynamic on my project and I had capitalized key names in my yaml files.

Would it be ok if TryGetValueByKeyAndType tried both capitalized and decapitalized keys and only then decide to return empty DynamicYaml?

Something like this:

    private bool TryGetValueByKeyAndType(string key, Type type, out object result)
    {
        if (mappingNode == null)
        {
            return FailToGetValue(out result);
        }
        var decapitalizedKey = new YamlScalarNode(key.Decapitalize());
        var capitalizedKey = new YamlScalarNode(key.Capitalize());

        if(TryGetValueByYamlKeyAndType(decapitalizedKey, out result)) 
            return true;

        if (TryGetValueByYamlKeyAndType(capitalizedKey, out result))
            return true;

        return IsNullableType(type) ? SuccessfullyGetValue(new DynamicYaml((YamlNode)null), out result) : FailToGetValue(out result);
    }

    private bool TryGetValueByYamlKeyAndType(YamlScalarNode yamlKey, out object result)
    {
        if (mappingNode.Children.ContainsKey(yamlKey))
        {
            var value = mappingNode.Children[yamlKey];
            if (YamlDoc.TryMapValue(value, out result))
            {
                return true;
            }
        }
        result = null;
        return false;
    }

Nuget update

Hi,

If possible, can you update the packages (including YamlDotNet.Dynamic) on Nuget?

Thanks

Convert YamlDotNet to a Portable Class Library

Would it be possible to convert YamlDotNet to a Portable Class Library and publish this version on NuGet? This will allow it to be used in cross-platform projects (Mono, Windows Store, Windows Phone).

http://msdn.microsoft.com/en-us/library/vstudio/gg597391(v=vs.100).aspx

Depending on how many non-portable types/methods used it could be as easy as installing VSCommands and using "Convert to Portable Library" context action.

I checked and it seems that YamlDotNet could be converted as easy as that. YamlDotNet.Dynamic would require changing minimum target platform to 4.5 afterwards in PCL project options.

Visual Studio 2012 add-in support

It seems that the add-in no longer supports Visual Studio 2012. Would it be possible to roll this change back?

http://visualstudiogallery.msdn.microsoft.com/34423c06-f756-4721-8394-bc3d23b91ca7
(there is another complaint in the comment section of that page)

It would be nice, since Visual Studio 2012 is a milestone version where Microsoft stopped supporting multiple products (e.g. XNA, Windows Phone 7.1). Visual Studio 2013 is a less important version released to fill the gap between version 2012 and version 2014 (coming this September).

Thank you.

Is it possible to YamlAlias enum values?

I was wondering if YamlAlias could be applied to enum values like they can with object properties.

One useful application of this would be for strings that can't be a variable name. For example:

enum Buttons
{
    ...

    [YamlAlias("go-home")]
    [Description("go-home")]
    GoHome,

    ...
}

This way the string "go-home" can be deserialized into an enum value.

Yaml schema validator?

I just wanted to say great job on this library. It is excellent and really high quality. I've just incorporated it into my latest project.

Have you thought about adding a YAML schema validator similar to Kwalify?

Duplicate reference anchor error

I found this while serializing and deserializing an object that had two properties, both of which had the same reference.

I'm getting a System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary:

at YamlDotNet.RepresentationModel.Serialization.YamlSerializer.DeserializeValue(EventReader reader, Type expectedType, DeserializationContext context) in YamlSerializer.cs: line 307

This can be reproduced with the following:

[Test]
public void CanIMakeItFail()
{
    object obj1 = "abc";
    object obj2 = "obj1;

    object[] objects = new objects[2];
    objects[0] = obj1;
    objects[1] = obj2;

    object[] result = SerializeThenDeserialize(objects);
}

private T SerializeThenDeserialize<T>(T input)
{
    Serializer serializer = new Serializer();
    TextWriter writer = new StringWriter();
    serializer.Serialize(writer, input, typeof(T));

    string serialized = writer.ToString();
    Console.Out.WriteLine("serialized = {0}", serialized);

    return YamlSerializer.Create(input).Deserialize(new StringReader(serialized));
}

The Console.Out.WriteLine of the serialized YAML prints:

serialized = - *o0
- *o0

Mixed line endings

I have autocrlf set to true since I'm on windows but when checking out the branches I get some files that have mixed line endings (parts with CRLF and parts with LF). Why is this happening? How have the files been committed?

Serializing also fields and not just properties will make life easier

I have an small problem, I'm using structures for 2 purposes, deserialize and serialize from Yaml files but also to download it to a realtime system which needs Marshaled variables. So for example

public struct Configuration
    {
        public NameValue Name;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
        public BoolValue[] AllowedInDirection; 
   }

In this case the BoolValue is something that I need to Marshal in order to been able to download it to the final component. Converting this in a property in order to been able to use the Deserializer and Serializer is quite big work, I will need to create different structures for the realtime component and for the YAML file and that is not go.

So, why not to make this marvelous component so that it will be also possible to serialize a deserialize fields and not just properties inside a class or structure.

Environment.NewLine is treated as two separate line breaks

Environment.NewLine returns "\r\n" on Windows-based systems, but it is being treated as two separate line breaks when emitting a string containing those breaks. Emitting a Scalar with a Literal style, whose value is a string containing such a line break, and then re-parsing it, will result in a different string from the original.

Example code demonstrating this: https://dotnetfiddle.net/XKwL1J

Serialise Object Graph Sample Not Compiling

Hi,

I wanted to use YamlDotNet but i'm restricted to Netfx 3.5 so Dynamics are out of the window... I have created a sample graph to serialise but the sample no longer compiles as the constructor signature for the Serializer class has changed.

How do you construct an instance of the Serializer class without the dynamics.

Thanks
Dave

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.