Search code examples
c#serialization

How to serialize to strings only


I would like the output of serialization of properties of an object to be strings, even if they are int properties or bool properties.

using System;
using System.Text.Json;

public class Program
{
    public static void Main()
    {
        var myObj = new MyObj();
        var result = JsonSerializer.Serialize(myObj);
        Console.WriteLine(result); 
    }       
}

public class MyObj
{
    public MyObj()
    {
        Version = 10;
    }
    public int Version {get;set;}   
}

The above outputs

{ "Version" : 10 }

I'd like it to output

{ "Version" : "10" }

Changing the Version type in MyObj to an int creates an exception

Before I change the Version to a string, and save the number as a string (eg Version = "10";), is this achievable via the serialization process?


Solution

  • Here's an example of using a custom converter on the class level:

    using System;
    using System.Text.Json;
    using System.Text.Json.Serialization;
    
                        
    public class Program
    {
        public static void Main()
        {
            var m = new MyObj();
            Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(m));
        }
    }
    
    [JsonConverter(typeof(MyObjConverter<MyObj>))]
    public class MyObj
    {
        public MyObj()
        {
            Version = 10;
            Data = "Test";
            IsTrue = false;
            
        }
        public int Version {get;set;}
        public string Data {get; set;}
        public bool IsTrue {get; set;}
        public bool? IsFalse {get; set;} = null;
        public MyObj2 MyO2 {get; set;} = new MyObj2 { Age = 30, IsOld = false };
    }
    
    [JsonConverter(typeof(MyObjConverter<MyObj2>))]
    public class MyObj2
    {
        public int Age {get; set;} = 2;
        public bool IsOld {get; set;} = true;
    }
    
    
    public class MyObjConverter<T> : JsonConverter<T>
    {
            public override T Read(
                ref Utf8JsonReader reader,
                Type typeToConvert,
                JsonSerializerOptions options) =>
                    throw new NotImplementedException();
    
            public override void Write(
                Utf8JsonWriter writer,
                T myObj,
                JsonSerializerOptions options)
            {
                writer.WriteStartObject();
                foreach(var prop in myObj.GetType().GetProperties())
                {
                    if(prop.PropertyType == typeof(Boolean) || prop.PropertyType == typeof(int))
                    {
                        writer.WriteString(prop.Name, prop.GetValue(myObj, null)?.ToString().ToLower());
                    }
                    else
                    {
                        writer.WritePropertyName(prop.Name);
                        writer.WriteRawValue(System.Text.Json.JsonSerializer.Serialize(prop.GetValue(myObj, null), options));
                    }
                }
                writer.WriteEndObject();        
            }
    }
    

    DotNet Fiddle