0

As known it's better to use string format to serialize decimal number. https://stackoverflow.com/a/38357877/4805491

Many services send decimal values as strings and Json.NET deserializes it well.

But I can't find how to serialize decimal with string format?

Should I make custom JsonConverter for all decimal numbers? Or there are ways to do it with default Json.NET opportunities?

Updated

I need this test to be passed.

So, I need to replace all decimal values with string values when or after JToken.FromObject( ... ) is called.

var json = await Client.RequestJsonAsync( desc, default );
var obj = json.ToObject<MyObject>();
var json2 = JToken.FromObject( obj );
Assert.IsTrue( JToken.DeepEquals( json, json2 ), "Jsons are not equal" );

Unfortunately there is no (or I can't find) method to all replace all nodes in hierarchy. JToken.Replace only replaces itself. Also I don't see a way to iterating within hierarchy.

Denis535
  • 3,407
  • 4
  • 25
  • 36
  • 1
    Please see [Json.net serialize numeric properties as string](https://stackoverflow.com/q/39526057). The answer is specifically for `int`, just change it to `decimal` and you should be good. Also [Convert long number as string in the serialization](https://stackoverflow.com/q/17369278) and [JsonSerializer - serialize decimal places with 'N2' formatting](https://stackoverflow.com/q/17871720). Do those answer your question? – dbc Jun 10 '19 at 23:06

1 Answers1

0
    public static JToken FromObject(object obj) {
        var settings = new JsonSerializerSettings();
        settings.Converters.Add( new DecimalToStringConverter() );
        var serializer = JsonSerializer.CreateDefault( settings );
        return JToken.FromObject( obj, serializer );
    }


public class DecimalToStringConverter : JsonConverter {

    public override bool CanRead => false;
    public override bool CanWrite => true;


    public override bool CanConvert(Type type) {
        return type == typeof( decimal ) || type == typeof( decimal? );
    }

    public override object ReadJson(JsonReader reader, Type type, object existingInstance, JsonSerializer serializer) {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object instance, JsonSerializer serializer) {
        var number = (decimal) instance;
        writer.WriteValue( number.ToString( CultureInfo.InvariantCulture ) );
    }


}
Denis535
  • 3,407
  • 4
  • 25
  • 36