Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YamlDotNet deserialize integer as numeric not as string

Tags:

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);
like image 936
x y Avatar asked May 25 '18 11:05

x y


1 Answers

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.

like image 158
Phyxx Avatar answered Oct 11 '22 18:10

Phyxx