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.
-
2stackoverflow.com/questions/37475997/…Pepernoot– Pepernoot2016-09-16 07:34:26 +00:00Commented Sep 16, 2016 at 7:34
-
2@CodeJoy: That seems pretty DataTable-focused to me - I can't see how any of those answers are going to help the OP.Jon Skeet– Jon Skeet2016-09-16 07:41:13 +00:00Commented Sep 16, 2016 at 7:41
-
See Convert long number as string in the serialization.dbc– dbc2016-09-16 07:47:34 +00:00Commented Sep 16, 2016 at 7:47
-
Sorry @CodeJoy, but I was thinking of something "more automatic", like a ContractResolver or something like this. I wouldn't like to convert manually my model object into a JObject with all properties as strings. I will use this solution as a last resource, cause it works. Anyway thank you for your help!! ;)tesgu– tesgu2016-09-16 07:50:05 +00:00Commented Sep 16, 2016 at 7:50
-
@dbc Tested and works like a charm. Perfect!!tesgu– tesgu2016-09-16 07:53:42 +00:00Commented Sep 16, 2016 at 7:53
Add a comment
|
1 Answer
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));
}
}