Json.net将数字属性序列化为字符串 [英] Json.net serialize numeric properties as string
问题描述
我正在使用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
.我已经尝试过了,它可以正常工作-它又快又脏,您几乎可以肯定要扩展它以支持其他数字类型(long
,float
,double
,decimal
等),但是应该可以你要去
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屋!