10

I am using JsonConvert.SerializeObject to serialize a model object. The server expects all fields as strings. My model object has numeric properties and string properties. I can not add attributes to the model object. Is there a way to serialize all property values as if they were strings? I have to support only serialization, not deserialization.

tesgu
  • 125
  • 1
  • 1
  • 4
  • 2
    http://stackoverflow.com/questions/37475997/convert-int-to-string-while-serialize-object-using-json-net – Pepernoot Sep 16 '16 at 07:34
  • 2
    @CodeJoy: That seems pretty DataTable-focused to me - I can't see how any of those answers are going to help the OP. – Jon Skeet Sep 16 '16 at 07:41
  • See [Convert long number as string in the serialization](https://stackoverflow.com/questions/17369278/convert-long-number-as-string-in-the-serialization). – dbc Sep 16 '16 at 07:47
  • Sorry @CodeJoy, but I was thinking of something "more automatic", like a ContractResolver or something like this. I wouldn't like to convert manually my model object into a JObject with all properties as strings. I will use this solution as a last resource, cause it works. Anyway thank you for your help!! ;) – tesgu Sep 16 '16 at 07:50
  • @dbc Tested and works like a charm. Perfect!! – tesgu Sep 16 '16 at 07:53

1 Answers1

23

You can provide your own JsonConverter even for numeric types. I've just tried this and it works - it's quick and dirty, and you almost certainly want to extend it to support other numeric types (long, float, double, decimal etc) but it should get you going:

using System;
using System.Globalization;
using Newtonsoft.Json;

public class Model
{
    public int Count { get; set; }
    public string Text { get; set; }

}

internal sealed class FormatNumbersAsTextConverter : JsonConverter
{
    public override bool CanRead => false;
    public override bool CanWrite => true;
    public override bool CanConvert(Type type) => type == typeof(int);

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

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

class Program
{
    static void Main(string[] args)
    {
        var model = new Model { Count = 10, Text = "hello" };
        var settings = new JsonSerializerSettings
        { 
            Converters = { new FormatNumbersAsTextConverter() }
        };
        Console.WriteLine(JsonConvert.SerializeObject(model, settings));
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194