Json.net将数字属性序列化为字符串

10
我正在使用JsonConvert.SerializeObject来序列化一个模型对象。 服务器希望所有字段都是字符串。我的模型对象有数值属性和字符串属性。我无法向模型对象添加属性。是否有一种方法可以将所有属性值序列化为字符串?我只需要支持序列化,不需要反序列化。

2
http://stackoverflow.com/questions/37475997/convert-int-to-string-while-serialize-object-using-json-net - Pepernoot
2
@CodeJoy:对我来说,这似乎非常侧重于DataTable - 我看不出这些答案中有任何一个会帮助OP。 - Jon Skeet
抱歉@CodeJoy,但我在考虑一些“更自动化”的东西,比如ContractResolver或类似的东西。我不想手动将我的模型对象转换为一个JObject,并将所有属性都作为字符串。我会把这个解决方案作为最后的资源使用,因为它可以工作。无论如何,谢谢你的帮助!! ;) - tesgu
@dbc 经过测试,完美运行。太棒了!! - tesgu
1个回答

24

您甚至可以为数字类型提供自己的JsonConverter。我刚尝试了一下,它可以工作 - 它很快速和简单,但您几乎肯定希望将其扩展以支持其他数字类型(longfloatdoubledecimal等),但这应该能让您开始:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接