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.

5
  • 2
    stackoverflow.com/questions/37475997/… Commented Sep 16, 2016 at 7: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. Commented Sep 16, 2016 at 7:41
  • See Convert long number as string in the serialization. Commented Sep 16, 2016 at 7: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!! ;) Commented Sep 16, 2016 at 7:50
  • @dbc Tested and works like a charm. Perfect!! Commented Sep 16, 2016 at 7:53

1 Answer 1

25

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));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.