Json.net serialize numeric properties as string

前端 未结 1 753
清酒与你
清酒与你 2020-12-03 23:16

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

相关标签:
1条回答
  • 2020-12-03 23:26

    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));
        }
    }
    
    0 讨论(0)
提交回复
热议问题