Json.net serialize numeric properties as string(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
,即使是数字类型.我刚刚尝试过,它可以工作 - 它又快又脏,而且您几乎肯定想扩展它以支持其他数字类型(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 将数字属性序列化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Json.net 将数字属性序列化为字符串


- 带问号的 nvarchar 列结果 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 使用 rss + c# 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01