Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.net serialize numeric properties as string

Tags:

json

c#

json.net

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.

like image 782
tesgu Avatar asked Sep 16 '16 07:09

tesgu


People also ask

What is difference between Stringify and serialize?

stringify() ignores functions/methods when serializing. JSON also can't encode circular references. Most other serialization formats have this limitation as well but since JSON looks like javascript syntax some people assume it can do what javascript object literals can.

What is serializing in JSON?

Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). Serialization is the process of converting the state of an object, that is, the values of its properties, into a form that can be stored or transmitted.

What is Jsonproperty annotation C#?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.


1 Answers

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));
    }
}
like image 118
Jon Skeet Avatar answered Sep 23 '22 08:09

Jon Skeet