Json.net 将数字属性序列化为字符串 [英] Json.net serialize numeric properties as string

查看:12
本文介绍了Json.net 将数字属性序列化为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 JsonConvert.SerializeObject 序列化模型对象.服务器期望所有字段都是字符串.我的模型对象具有数字属性和字符串属性.我无法向模型对象添加属性.有没有办法像字符串一样序列化所有属性值?我必须只支持序列化,不支持反序列化.

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.

推荐答案

您可以提供自己的 JsonConverter,即使是数字类型.我刚刚尝试过,它可以工作 - 它又快又脏,而且您几乎肯定想扩展它以支持其他数字类型(longfloatdoubledecimal 等),但它应该可以帮助您:

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

这篇关于Json.net 将数字属性序列化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆