0

I have implemented a EANCode13 class with a constructor with a parameter like this:

public class EAN13Code {
  public EAN13Code(string value) {
      // validate it 
  }

  [JsonConstructor]
  public EAN13Code(long value) {
     // validate it
  }
}
public class ApiResponse
{
    public EAN13Code Code { get; }

    [JsonConstructor]
    public ApiResponse(EAN13Code code) {
       Code = code;
    }
}

and a JSON like this:

{
   "code" : 978020137962
}

Trying to deserialize simply like this doesn't work:

var reponse = JsonSerializer.Deserialize<ApiResponse>(json);

What do I need to do make it work?

Do I need a custom Json Converter? Writing one is easy but isn't there a simpler or better way?

Is there a library which can help?

Don Box
  • 3,166
  • 3
  • 26
  • 55
  • There's no `implicit` operator in your code. But even if there were I don't believe `System.Text.Json` would pick up on it, so you will need to write a custom `JsonConverter`. The JSON corresponding to `ApiResponse` would look like `{ "code" : { "value" : 978020137962 } }`. – dbc Aug 06 '21 at 20:15
  • Thanks. I removed that part from the title. Using an implicit operator was one of the things I tried and didn't work. So it appears JsonConverter is the only way? Could there be another way to at least not create a JsonConverter for all the objects? Like a common JsonConverter using maybe implicit operators – Don Box Aug 07 '21 at 04:40

0 Answers0