Giter Site home page Giter Site logo

sharpyaml's Introduction

SharpYaml Build Status NuGet

SharpYaml is a .NET library that provides a YAML parser and serialization engine for .NET objects, compatible with CoreCLR.

NOTICE:

This project is no longer actively maintained since 2016, but it's still accepting Pull-Requests.

Small improvements and fixes are welcome, but big refactoring won't likely be.

Please, open an issue in case you are not sure about the changes you want to bring before working on a PR.

Usage

var serializer = new Serializer();
var text = serializer.Serialize(new { List = new List<int>() { 1, 2, 3 }, Name = "Hello", Value = "World!" });
Console.WriteLine(text);

Output:

List:
  - 1
  - 2
  - 3
Name: Hello
Value: World!

Features

SharpYaml is a fork of YamlDotNet and is adding the following features:

  • Supports for .netstandard2.0
  • Memory allocation and GC pressure improved
  • Completely rewritten serialization/deserialization engine
  • A single interface IYamlSerializable for implementing custom serializers, along IYamlSerializableFactory to allow dynamic creation of serializers. Registration can be done through SerializerSettings.RegisterSerializer and SerializerSettings.RegisterSerializerFactory
    • Can inherit from ScalarSerializerBase to provide custom serialization to/from a Yaml scalar
  • Supports for custom collection that contains user properties to serialize along the collection.
  • Supports for Yaml 1.2 schemas
  • A centralized type system through ITypeDescriptor and IMemberDescriptor
  • Highly configurable serialization using SerializerSettings (see usage)
    • Add supports to register custom attributes on external objects (objects that you can't modify) by using SerializerSettings.Register(memberInfo, attribute)
    • Several options and settings: EmitAlias, IndentLess, SortKeyForMapping, EmitJsonComptible, EmitCapacityForList, LimitPrimitiveFlowSequence, EmitDefaultValues
    • Add supports for overriding the Yaml style of serialization (block or flow) with SerializerSettings.DefaultStyle and SerializerSettings.DynamicStyleFormat
  • Supports for registering an assembly when discovering types to deserialize through SerializerSettings.RegisterAssembly
  • Supports a IObjectSerializerBackend that allows to hook a global rewriting for all YAML serialization types (scalar, sequence, mapping) when serializing/deserializing to/from a .NET type.

Download

SharpYaml is available on NuGet

License

MIT

sharpyaml's People

Contributors

aaubry avatar bdovaz avatar bf-sharris avatar cinchoo avatar ctaggart avatar daniel15 avatar jnystad avatar johshoff avatar kryptos-fr avatar kzu avatar martindevans avatar maxvoxel8 avatar pathogendavid avatar peter-dolkens avatar peterdavidson avatar roji avatar savornicesei avatar schnutzel avatar sescalada avatar turee avatar udaken avatar uwx avatar xen2 avatar xoofx 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

sharpyaml's Issues

Better serialization of tuples

Right now, SharpYaml serializes tuples as plain structs:

Item1: 1
Item2: 2
Item3: 3
Item4: Hello, world!

While this is great and gets the job done, it is particularly lacking in two aspects:

  1. The names from named tuples are not used
  2. I would argue that tuples should be sequences. This would have the added benefit of making the generated YAML more similar to the C# tuple syntax, such as the YAML below:
[1, 2, 3, 'Hello, world!']

I've written a serializer to perform the latter: ValueTupleSerializer

It covers my needs, although it doesn't support the following yet:

  • Nested tuples (The C# compiler generates these for tuples that are too long to fit into a single ValueTuple.)
  • Old school System.Tuple
  • Named tuples (I started to add them, but I am pretty sure I'd need to modify SharpYaml to support it.)

@xoofx, would you be interested in a pull request that adds support with tuples? If so, I can fix the few things above and submit a pull request.

I will note, however, that this would break backwards compatibility with previously serialized tuples. It might be possible to detect the old tuple format when deserializing and fall back to the old method, but I haven't given it much thought yet.

SharpYaml serialization can't handle System.Guid

When I was evaluating SharpYaml for my needs, I found that it doesn't handle GUIDs. Rather than serialize the GUID, it serializes and empty object. I would at least expect it to throw an exception, alerting me to the fact that the serialized data is incomplete.

Below is a minimal program to demonstrate the issue. The issue occurs both when the GUID is a member of a type being serialized and when it is serialized alone.

using System;
using SharpYaml.Serialization;

namespace YamlPlayground
{
    class SharpYamlGuidTest
    {
        public struct MyStructWithGuid
        {
            public Guid MyGuid;

            public MyStructWithGuid(Guid myGuid)
                => MyGuid = myGuid;
        }

        public static void SerializeGuidWithSharpYaml()
        {
            var serializerSettings = new SerializerSettings()
            {
                EmitTags = false
            };
            var serializer = new Serializer(serializerSettings);

            Guid guid = Guid.Parse("f8dd32bf-ebb3-4a64-982e-9450398cfaea");

            string yaml1 = serializer.Serialize(guid);
            Console.WriteLine(yaml1);
            // Actual: 
            //  {}
            // Expected:
            //  f8dd32bf-ebb3-4a64-982e-9450398cfaea
            //  ...

            string yaml2 = serializer.Serialize(new MyStructWithGuid(guid));
            Console.WriteLine(yaml2);
            // Actual: 
            //  MyGuid: {}
            // Expected:
            //  MyGuid: f8dd32bf-ebb3-4a64-982e-9450398cfaea

            Guid guid1 = serializer.Deserialize<Guid>(yaml1);
            Guid guid2 = serializer.Deserialize<MyStructWithGuid>(yaml2).MyGuid;

            Console.WriteLine(guid1 == guid);
            Console.WriteLine(guid2 == guid);
            // Actual:
            //  false
            //  false
            // Expected:
            //  true
            //  true
        }
    }
}

Cannot set YamlMemberAttribute.Order as an additional argument

First of all thanks for SharpYaml! If I want to set both the name and the order for serializing a property like this:

[YamlMember("someprop", Order = 1)]
public string SomeProperty { get; set; }

I get a compiler error:

"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type." See also this SO answer that references the spec: https://stackoverflow.com/a/3192882

The solution is to either create an overload for the YamlMemberAttribute constructor so that you can set both name and order, or to change the type of Order from "int?" to "int". The last solution is the most flexible but I don't know what the consequences are of changing Order's type (i.e. if null has a special meaning).

.NET Standard 1.0

Now minimal .NET Standard version for SharpYaml is 1.6. For example, Newtonsoft.JSON supports 1.0.
Is it possible to migrate to 1.0 or 1.3?

Serializer does not preserve members order

open SharpYaml.Serialization

let serSettings = SerializerSettings(EmitDefaultValues=true, EmitTags=false, SortKeyForMapping=false)
let serializer = Serializer(serSettings)

[<CLIMutable>] type T = { Z_1: int; A_2: int; P_3: int }

let t = { Z_1 = 1; A_2 = 2; P_3 = 3 }
serializer.Serialize t

Result is:

A_2: 2
P_3: 3
Z_1: 1

However, I expect the following:

Z_1: 1
A_2: 2
P_3: 3

BTW, YamlDotNet does preserve the members order.

Can't Run at Windows XP

I make a simple WPF application with .NET4 at Windows 10, and copy all .exe / .dll to a Windows XP at a VirtualBox VM.
It can run good at Windows 10, but not run at Windows XP.

Serializer emits incorect data on second attempt

class Data
    {
        public string Text { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var data = new Data { Text = "text" };

            var s = new Serializer();

            var a1 = s.Serialize(data);
            var a2 = s.Serialize(data);

            Console.WriteLine(a1 == a2);
        }
    }

Result is False
Expected is true

Can I Read/Write Anchor Names Somehow?

I want to be able to control the names of anchors being emitted, more specifically:

  1. How do I control the output name of an anchor?
  2. How can I get the anchor name after dezerialisation?
public class MyNode
{
  public string Name { get; set; }
  public string  MyScalar { get; set; }
}

public class MyNodeList
{
  public IList<MyNode> Items { get; set; }
}

var node = new MyNode 
{
  [YamlAnchor] // this attribute doesn´t exist, but is there something similar?
  Name = "i_want_this_to_be_the_anchor_name",
  MyScalar = "hello"
};

var list = new MyNodeList() {
  node,
  node,
  node,
  node
}

How can I get this:

MyNode:
  - &i_want_this_to_be_the_anchor_name
    Name: some_name
    MyScalar: hello

Items:
  - *i_want_this_to_be_the_anchor_name
  - *i_want_this_to_be_the_anchor_name
  - *i_want_this_to_be_the_anchor_name
  - *i_want_this_to_be_the_anchor_name

instead of this:

MyNode:
  - &o2
    Name: some_name
    MyScalar: hello

Items:
  - *o2
  - *o2
  - *o2
  - *o2

Inaccurate SyntaxErrorException exception information

I'm using the library to validate if a file is correctly formatted or not. Here is the simplified code:

public static bool Validate(string filename)
{
    try
    {
        var content = File.ReadAllText(filename);
        var yaml = new YamlStream();
        yaml.Load(new StringReader(content));
        return true;
    }
    catch(SyntaxErrorException ex)
    {
        Console.Error.WriteLine($"{filename} invalid: {ex.Start.ToString()}");
        return false;
    }
}

When I use the following content:

name: alex
 age: 1 #just one space to trigger error

The following is written to the console:

test.yaml invalid: Lin: 1, Col: 4, Chr: 15

I would expect Line number to be 2. Similarly column and char do not appear correct either.

Serialize the dynamic object.

It will get the non-yaml string when serialize the dynamic object.

dynamic o = new ExpandoObject();
o.name = "foo";
var serializer = new Serializer();
System.Console.WriteLine(serializer.Serialize(o));

will get

!System.Dynamic.ExpandoObject,%2520System.Linq.Expressions,%2520Version=4.2.1.0,%2520Culture=neutral,%2520PublicKeyToken=b03f5f7f11d50a3a
name: foo

Env(dotnet --info):

.NET Core SDK (reflecting any global.json):
 Version:   2.1.400
 Commit:    8642e60a0f

Runtime Environment:
 OS Name:     Mac OS X
 OS Version:  10.13
 OS Platform: Darwin
 RID:         osx.10.13-x64
 Base Path:   /usr/local/share/dotnet/sdk/2.1.400/

Host (useful for support):
  Version: 2.1.2
  Commit:  811c3ce6c0

.NET Core SDKs installed:
  2.1.400 [/usr/local/share/dotnet/sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.2 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.2 [/usr/local/share/dotnet/shared/Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.1.2 [/usr/local/share/dotnet/shared/Microsoft.NETCore.App]

How do I get Serialize() to stop putting out anchor and reference labels?

I basically want the output to be the same as the input and this code almost gets there except for the anchor and reference labels on the values of title and address.

string YamlData = YamlData =
    @"
    first: 'John'
    last: Smith
    title: 
    address: 
    list:
        - false
        - false
        - false";
var YamlSerializer = new SharpYaml.Serialization.Serializer();
Dictionary<object, object>  DocumentData = YamlSerializer.Deserialize<Dictionary<object, object>>(YamlData);
YamlSerializer.Settings.SortKeyForMapping = false;
YamlSerializer.Settings.EmitAlias = true;
YamlSerializer.Settings.EmitTags = true;

string YamlData2 = YamlSerializer.Serialize(DocumentData);
Debug.WriteLine(YamlData2);

Configure Flow/Block serialization per property

I have the following class:

public class Post {
  public List<String> Tags { get; set; }
  public List<Author> Authors { get; set; }
}

Is it possible to make Tags list being serialized as Flow and Authors as Block?

Emit empty string instead of null

I am serializing the following object:

public class Post {
  public Int32? Id { get; set; }
  public String Title { get; set; }
}

Post post = new Post { Id = null, Title = "Using SharpYaml" };

var result = serializer.Serialize(post);

On the output I get the following:

id: null
title: Using SharpYaml

Is it possible to display an empty string on Id when its value is null, e.g:

id: 
title: Using SharpYaml

Round trip serialization problem

When a floating point value for example 1.0 is serialized the resulting string is "1". Now when this value is deserialized it's type changes to integer. This is a problem when type needs to remain same.

I will make pull request which fixes this.

Escape #

Is there a way to escape # in e.g.

color: #aabbcc

Can you get a node by using a string path somehow?

Such as "category.object.parameter" retrieving the node at

category:
    object:
        parameter: "hello"

In all other YAML libraries I've used in other languages one can get a node by simply entering the path to it as a string in a get function, is there a feature like that here?

ObjectFactory and Unity

Hello.

Question: 1

I want that all my objects from a YAML file will be resolved through Unity container. I have chosen the SerializerSettings.ObjectFactory approach because I don’t want to manually register my custom serializer for each type in the YAML file (there are a lot of types).

settings.ObjectFactory = new LambdaObjectFactory (type => Unity.Resolve (type),
 new DefaultObjectFactory ());

But my factory is called for all objects from YAML, even for List<>. Surely I can register List<> in Unity to resolve it. But I think I’ve missed some better solution.

Question: 2

If I resolve from Unity class Car:

class Car
{
   public Door Left;

   public (Door left) 
   {
        this.Left = left;
   }
}

class Door
{
   public string Color;
}

The field of type Door will be resolved too so the memory for it will be allocated.
However the YAML parser will create the Door object again during deserialization serializer.Deserialize<Car> the file:

Left: 
  Color: Red

Can I configure such things?

Also I can assume that Deserialization term means that all objects are created only during deserialization process and not otherwise. But how can I use Unity in this case?

Cannot Serialize Decimal

Seems like decimals simply don't work with SharpYaml :(

This test fails:

[TestMethod]
public void AreDecimalsBroken_YesTheyAre()
{
  var serializer = new Serializer(new SerializerSettings
  {
     EmitTags = true,
  });

  var builder = new StringBuilder();
  serializer.Serialize(new StringWriter(builder), new { Value = 1.023m });
}

With a stack trace which ends up in SharpYaml.Serialization.Serializers.PrimitiveSerializer.ConvertTo

Tracking that down you have:

case TypeCode.Decimal:
    text = AppendDecimalPoint(((decimal)value).ToString("R", CultureInfo.InvariantCulture));

The docs specify that R is not a valid format string for decimal! A quick unit test shows that this (based off this SO question) produces sensible results:

const decimal D = 23534623451.0232342352463856743367556835m;
var text = D.ToString("#.#############################", CultureInfo.InvariantCulture);
Console.WriteLine(text);
//Prints: 23534623451.023234235246385674

So I guess you probably want to replace that "R" format string :)

SerializerSettings.DefaultStyle not working

The SerializerSettings.DefaultStyle property seems to have no effect. The following code still produces a block syntax (SharpYaml v1.6.5.0):

var serializer = new Serializer(new SerializerSettings { DefaultStyle = YamlStyle.Flow });
var text = serializer.Serialize(new { List = new List<int> { 1, 2, 3 }, Name = "Hello", Value = "World!" });
Console.WriteLine(text);
// Outputs:
// List:
//   - 1
//   - 2
//   - 3
// Name: Hello
// Value: World!

Any idea why?

How to get token locations?

def settings = SerializerSettings() <- 
    { EmitDefaultValues = true; 
      EmitTags = false; 
       SortKeyForMapping = false };
def serializer = Serializer(settings);
def node = serializer.Deserialize(StringReader(text));

node contains Dictionary<object, object> where locations are not present. Is there a way to get them? I mean something like { Start = (1, 0), End = (1, 5) } for Bar: 2 in

Foo: 1
Bar: 2

Hard to figure out recursive iteration

I've been trying to figure out how I could write some code to iterate over a parsed .yaml document and it is really hard to understand anything without any documentation...

Could someone please write a piece of code like below and attach it to main README.md (or at least provide a pointer to a test case doing something alike).

let yamlSerializer = SharpYaml.Serialization.Serializer ()
use yamlFile = File.OpenText "test.yaml"
let yamlDoc = yamlSerializer.Deserialize yamlFile

let rec recurseYaml yaml = 
    yamlDoc
    |> Seq.iter (fun (key, value) ->
        match value with
        | DictionaryValueType d -> recurseYaml d
        | ArrayValueType a -> printfn "%s: %A" 
        | StringValueType s -> printfn "%s: %s" key s
        | IntValueType i -> printfn "%s: %d" key i
    ...

recurseYaml yamlDoc

Add YamlSerializer class name

It would match better .NET naming pattern for serializers and will reduce confusion as to what kind of serializer it actually is.

property IsUnicode in Emmiter class always returns false

Comparing various utf encodings coming from outside world to these few defaults provided by .Net framework is very likely to fail. In fact both StringWriter and a StreamWriter returned from File.CreateText are not recognized as Unicode.

I'm not sure what is the correct way to do this but

private bool IsUnicode => output.Encoding.WebName.Contains("utf");

seems to work fine.

Help class header

pls help! i always get this kind of weird text behind my class object

!Object.Test,%2520Object.Test,%2520Version=1.0.0.0,%2520Culture=neutral,%2520PublicKeyToken=null
ObjectCollection:

Convert the properties names from snake_case to PascalCase

I am using snake_case on an YAML file and deserializing it as follows:

  serializer = new Serializer(new SerializerSettings {
     DefaultStyle = YamlStyle.Block,              
     EmitAlias = false,
     IndentLess = true,
     NamingConvention = new DefaultNamingConvention(),
     PreferredIndent = 2,
     SortKeyForMapping = false            
  });

  var result = serializer.Deserialize(yaml);

I get an object where the properties names are still in snake_case like 'is_active', etc.

I need to convert the properties names from snake_case in the YAML to PascelCase in the deserialized object.

How can I do this?

Parsing anchors in Model namespace

I am having an issue loading documents that use anchors to duplicate scalar values though Model.YamlStream.Load(TextReader). A simple example of the format is:

field1: &data ABCD
field2: *data

It looks like YamlNode.ReadElement returns null when processing field2 which causes an exception in YamlMapping.Load.

How Do I Get A Custom Serializer To Work?

I tried to implement a custom serializer for Regex to work, but it doesn´t get executed, do I have to register or add it somewhere?

Regex serializer

public class RegexYamlSerializer : ScalarSerializerBase, IYamlSerializable
{
  public override object ConvertFrom(ref ObjectContext context, Scalar fromScalar)
    => new Regex(fromScalar.Value);

  public override string ConvertTo(ref ObjectContext objectContext)
  {
    object value = objectContext.Instance;

    if (value is Regex regex)
    { return regex.ToString(); }

    throw new YamlException($"Unable to serialize scalar [{value}] not supported");
  }
}

Attempt to use

public class MyNodeWithRegex
{
  public Regex  MyPattern { get; set; }
}

var node = new MyNodeWithRegex
{
  MyPattern = new Regex(@"[2][0]\d{2}[-]\d{2}[-]\d{2}"))
};

var serializer = new Serializer();
var result = serializer.Serialize(patterns);

Expected

    MyPattern: '[2][0]\d{2}[-]\d{2}[-]\d{2}'

Actual

    MyPattern: {}

Complex structs not serializing/deserializing

Since there's no real discussion board to ask about this, not sure where else to put this.

I'm trying to serialize and de-serialize more complex structs, in this case OxyColor, which is a custom version of Color for OxyPlot. I noticed in your tests you've got a basic Color struct, and I had no issue replicated that, but trying the same with with either Color or OxyColor will just give an error on de-serialization, and outputs "{}" when serialized.

Here's the basic test I was using in LinqPad:

void Main()
{
    var color = Color.SkyBlue;
    var oxyColor = OxyColors.SkyBlue;

    Console.WriteLine(color);
    Console.WriteLine(oxyColor);
    Console.WriteLine(color.ToString());
    Console.WriteLine(oxyColor.ToString());

    Console.WriteLine();

    var yamlSettings = new SerializerSettings();
    yamlSettings.RegisterAssembly(typeof (OxyColor).Assembly);
    yamlSettings.RegisterTagMapping("!OxyColor", typeof (OxyColor));
    yamlSettings.RegisterAssembly(typeof (Color).Assembly);
    yamlSettings.RegisterTagMapping("!Color", typeof (Color));

    var yaml = new Serializer(yamlSettings);

    Console.WriteLine(yaml.Serialize(color, typeof (Color)));
    Console.WriteLine(yaml.Serialize(oxyColor, typeof (OxyColor)));

    var value = yaml.Deserialize<TestColor>(@"Color: !Color {R: 135, G: 206, B: 235, A: 255}");
    Console.WriteLine(value is TestColor);
    Console.WriteLine(value.Color);
    Console.WriteLine(yaml.Serialize(value, typeof (TestColor)));

    Console.WriteLine(yaml.Deserialize<OxyColor>(@"!OxyColor {R: 135, G: 206, B: 235, A: 255}"));
    Console.WriteLine(yaml.Deserialize<OxyColor>(TestOxyColor2).ToString());
    Console.WriteLine(yaml.Deserialize<OxyColor>(TestOxyColor));
}

// Define other methods and classes here
class TestColor
{
    public Color Color { get; set; }
}

private const string TestOxyColor = @"---
!OxyColor
  A: 255
  B: 235
  G: 206
  R: 135
...";

private const string TestOxyColor2 = @"!OxyColor #ff87ceeb";

It will throw the following YamlException on line 24:

(Lin: 0, Col: 7, Chr: 7) - (Lin: 0, Col: 14, Chr: 14): Error while deserializing node [Mapping start [anchor = , tag = !Color, isImplicit = False, style = Flow]]"

Interestingly enough the inner exception is:

KeyNotFoundException: R

I've been trying to work through the source myself but honestly I'm getting a little lost in it >_<! Going to keep at it though. Hopefully you've got some input.

BTW thanks for having actual readable exceptions, it helped fix an issue I was having at first.

Also, don't want to start another issue for this, but I'm trying to understand what I'm doing wrong creating my own Schema to use with OxyColor. It doesn't even seem to want to notice there was a tag added by it, so I can't seem to get it to work at all. Here's a gist of my testing code.

SharpYaml dependencies

Latest version v1.6.3 has dependency on System.Reflection.TypeExtentions v.4.1.0.0
win10_-_fall_creators

nuspec say that you depend on system.reflection.typeextensions.4.3.0.nupkg or later.
There is a dll inside this NuGet package in lib\netstandard1.5\ that has version 4.1.1.0
win10_-_fall_creators

So, there is no way to use SharpYaml wihtout binding redirects =(
It is possible to fix it?

Deserialization reuses default List instead of creating new one

If a class i want to (de)serialize has an IEnumerable<T> property with default value set to some List, after deserialization, such property will have both items set by default and deserialized.

using a type TestClass:

class TestClass 
{
    IEnumerable<string> SomeSequence {get; set;} = new List<string>{"test"};
}

the following fails

[Test]
public void TestSerializeDeserialize()
{
	var serializer = new Serializer();
	var value = new TestClass();
	var serialized = serializer.Deserialize<TestClass>(serializer.Serialize(value));
	Assert.That(serialized, Is.EqualTo(value));
}

as serialized.SomeSequence is now equal to new List<string>{"test", "test"}.

However, if the default value is set to an array (new string[]) this does not occur.

Access to the actual value being serialized in IYamlSerializableFactory.TryCreate

Hello,
i have my own class type that "wrap" a List or a Dictionary,
it's a single type but at runtime it sometimes wrap a List and sometimes a Dictionary,
i'm trying to instruct SharpYaml to serialize this type with
SharpYaml.Serialization.Serializers.CollectionSerializer
or with
SharpYaml.Serialization.Serializers.DictionarySerializer
but to know which one should be used i need to access the actual value that is being serialized,
i'm trying to do this in my own YamlSerializableFactory but i cannot find a way to access the value that is being serialized.

Here is my cutom factory (vb.net):

Class CustomSerializerFactory
Implements SharpYaml.Serialization.IYamlSerializableFactory

     Public Function TryCreate(context As SharpYaml.Serialization.SerializerContext, typeDescriptor As SharpYaml.Serialization.ITypeDescriptor) As SharpYaml.Serialization.IYamlSerializable Implements SharpYaml.Serialization.IYamlSerializableFactory.TryCreate

        Dim value_to_serialize = Nothing '??? where to access the actual value that is being serialized?

        'consider only my own type, use sharpyaml default for others
        Dim my_type_value = TryCast(value_to_serialize, DictTree)
        If my_type_value Is Nothing Then
           Return Nothing
        End If

        'ask the object instance and return the right serializer for the actual state of the object
        If my_type_value.IsDictionary Then
           Return New SharpYaml.Serialization.Serializers.DictionarySerializer()
        Else
           Return New SharpYaml.Serialization.Serializers.CollectionSerializer()
        End If

        Return Nothing
     End Function
  End Class

Thank you in advice for your support!

Question: Can SharpYaml handle merging?

Yaml has support for merging which allows for sort-of templating in YAML:

---
- &CENTER { x: 1, y: 2 }
- &LEFT { x: 0, y: 2 }
- &BIG { r: 10 }
- &SMALL { r: 1 }

# All the following maps are equal:

- # Explicit keys
  x: 1
  y: 2
  r: 10
  label: center/big

- # Merge one map
  << : *CENTER
  r: 10
  label: center/big

- # Merge multiple maps
  << : [ *CENTER, *BIG ]
  label: center/big

- # Override
  << : [ *BIG, *LEFT, *SMALL ]
  x: 1
  label: center/big

Is this supported in SharpYaml?

PCL Profile 259?

Would it be easy for you guys to distribute 2 PCLs in your NuGet package, besides the current Profile 136, to also target Profile 259 ;)

Related to dotnet/fsharp#99 where PCLs from 4.5 and 4.0 dont play nice together

First line added to YAML file

I am serializing and object to YML and the first line on my YML file is:

!Proj.PostModel,%2520Proj,%2520Version=1.0.0.0,%2520Culture=neutral,%2520PublicKeyToken=null

Any idea where this comes from? How to avoid this being added to the YAML file?

[Question] Is there a way to output a string property using the multi-line block scalar styles (>, |)

Hi,

Subject pretty much covers it. I am trying to serialize a class with string properties and want to out put them in the block style without quotes and "\r" or "\n".

I have been trying to do it with the SerializerSettings like:

            var ocrTemplateType = typeof(OcrTemplate);
            settings.RegisterTagMapping("!OcrTemplate", ocrTemplateType);
            settings.Attributes.Register(ocrTemplateType.GetProperty(nameof(OcrTemplate.Text)), new YamlMemberAttribute(0));
            settings.Attributes.Register(ocrTemplateType.GetProperty(nameof(OcrTemplate.Text)), new YamlStyleAttribute(SharpYaml.YamlStyle.Block));

Cheers,
dfkeenan

Parse block with value gives SemanticErrorException

The following yaml I believe is valid (looking at e.g. bill-to at yaml.org). However, parsing it gives me a SemanticErrorException.

root: someValue
    blockKey: someOtherValue

Strangely, adding a comment (also valid) also gives SemanticErrorException but with another stack trace and error message.

root: someValue
    # A comment
    blockKey: someOtherValue

Here's a test:

        [Test]
        public void ParseValueAndBlock()
        {
            const string yaml =
@"root: someValue
    blockKey: someOtherValue
";

            var reader = new StringReader(yaml);
            var stream = new YamlStream();
            stream.Load(reader); // throws SemanticErrorException
        }

Tested with version 1.5.3.

Properties with [YamlIgnore] being accessed during serialization

[YamlIgnore] doesn't exactly work - properties having it are still invoked, and their results are discarded only afterwards.

For example, if a property with [YamlIgnore] throws an exception, this will make the serialization process abort.

To repro, go to the ContainsIgnore class in SerializationTests.cs and throw exceptions from the getter/setter. I've created a commit that demonstrates this for the original YamlDotNet here: roji/YamlDotNet@648463e

Parsing Int64 leads to crash

Hi,

First of all - thanks for amazing library.

Reallife use case: Merging app configs with long app_ids in content and loading resulting config.

Smallest repro:

var sr = new Serializer(new SerializerSettings() {EmitTags = false});
var map = sr.Deserialize<Dictionary<object, object>>("key: \"12345678901\"");
var newYaml = sr.Serialize(map);
var map2 = sr.Deserialize<Dictionary<object, object>>(newYaml);

Unhandled Exception: SharpYaml.YamlException: (Lin: 10, Col: 21, Chr: 625) - (Lin: 10, Col: 36, Chr: 640): Error while deserializing node [Scalar [anchor = , tag = , value = 169545139744270, style = Plain, isPlainImplicit = True, isQuotedImplicit = False]] ---> System.OverflowException: Value was either too large or too small for an Int32.
at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
at SharpYaml.Schemas.CoreSchema.b__14(Match m)
at SharpYaml.Schemas.SchemaBase.ScalarResolutionRule`1.Decode(Match m)
at SharpYaml.Schemas.SchemaBase.TryParse(Scalar scalar, Boolean parseValue, String& defaultTag, Object& value)
at SharpYaml.Schemas.FailsafeSchema.TryParse(Scalar scalar, Boolean parseValue, String& defaultTag, Object& value)
at SharpYaml.Serialization.Serializers.PrimitiveSerializer.ConvertFrom(ObjectContext& context, Scalar scalar)
at SharpYaml.Serialization.Serializers.ScalarSerializerBase.ReadYaml(ObjectContext& objectContext)
at SharpYaml.Serialization.Serializers.RoutingSerializer.ReadYaml(ObjectContext& objectContext)
at SharpYaml.Serialization.Serializers.TagTypeSerializer.ReadYaml(ObjectContext& objectContext)
at SharpYaml.Serialization.Serializers.AnchorSerializer.ReadYaml(ObjectContext& objectContext)
at SharpYaml.Serialization.SerializerContext.ReadYaml(Object value, Type expectedType)

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.