Home > Software engineering >  deserialize integer into a string
deserialize integer into a string

Time:08-17

Is there a way to deserialize an integer into a string ? I need it for compatibility reason.

using System.Text.Json;
using System.Text.Json.Serialization;

namespace Abc.Test
{
    [JsonSerializable(typeof(OrderInfo), GenerationMode = JsonSourceGenerationMode.Metadata)]
    public partial class OrderInfoContext : JsonSerializerContext
    { }

    public partial class OrderInfo
    {
        public string UserReference { get; set; }
    }
    public class Program
    {
        static void Main(string[] args)
        {
            var json = @"{""UserReference"": 123}";  // <---- how having 123 deserialize as a string?

            var s = JsonSerializer.Deserialize(json, OrderInfoContext.Default.OrderInfo);
        }
    }
}

CodePudding user response:

In some cases it can make sense to separate your serialization objects (aka DTOs) from your domain objects. This give you several benefits:

  1. Allow your domain objects to have behavior defined, without affecting serialization.
  2. A place to handle any complicated changes to the model without losing backwards compatibility.
  3. Allow the serialization objects to fulfill requirements like public setters, without affecting the usage in the rest of the code.

Ex:

public class OrderInfoDTO
{ 
    public int UserReference { get; set; }
    public OrderInfo ToModel() => new OrderInfo(UserReference.ToString();
}
public class OrderInfo{
    public string UserReference {get;}
    public OrderInfo(string userReference) => UserReference = userReference;
}

CodePudding user response:

You can use a custom converter on a property. I'll look something like:

    public partial class OrderInfo
    {
        [JsonConverter(typeof(YourCustomConverter))]
        public string UserReference { get; set; }
    }
  • Related