1

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);
        }
    }
}
8
  • What is this json.Deserialize? can you show the code pls? Commented Aug 16, 2022 at 14:55
  • I have edited @Serge Commented Aug 16, 2022 at 15:12
  • What serializer are you using? I can not compile your code Commented Aug 16, 2022 at 15:25
  • It used source generators and net6 Commented Aug 16, 2022 at 15:25
  • I am sorry but what is a source generator? I never heard before . Can you post a link pls? Commented Aug 16, 2022 at 15:26

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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; }
    }

3 Comments

I use System.Text.Json and source generators not newtonsoft
@GuillaumeParis you can use custom converters with STJ.
Right ; it is more elegant to do JonasH solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.