5

I need to convert a yaml file to json format for validating it against a json schema. So I use yamldotnet to read the yaml file and json.net to serialize it into a string in json format. Unfortunately, after that, all numeric values are converted to string and validation goes wrong.

How can I avoid that?

Here is the code I use:

var t = File.ReadAllText(src);
var d = new YamlDotNet.Serialization.Deserializer();
var sr = new StringReader(t);
var o = d.Deserialize(sr);
var s = new Newtonsoft.Json.JsonSerializer();
var sb = new StringBuilder();
var sw = new StringWriter(sb);
s.Serialize(sw, o);
txt = sb.ToString();
Console.WriteLine("JSON Output: {0}", txt);
x y
  • 911
  • 9
  • 27
  • Can you post here your `d` object's properties? – Sá´‡M May 25 '18 at 11:16
  • d's properties are: 10 NodeDeserializers 5 TypeResolvers and as Non-Public members: backwardsCompatibleConfiguration and valueDeserializer of type *DefaultContainersNodeTypeResolver* – x y May 25 '18 at 11:52

1 Answers1

4

You can work around this by forcing the data types with tags in the source YAML e.g.

myObject:
  myIntValue: !!int 5
  myBoolValue: !!bool true
  myStringValue: hi there

It's not ideal, but can be a useful trick.

Phyxx
  • 15,730
  • 13
  • 73
  • 112