Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
259 views
Welcome To Ask or Share your Answers For Others

1 Answer

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));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...