2

Is it possible to create a decorator for a property of a class of type int so it serializes as a string?

I have

    public class MyClass
    {
        [SerializeAsString] //this is what I want
        public int StreetCode { get; set; }
    }

so when I call

var jsonRequest = JsonConvert.SerializeObject(myClass);

I want it to output the value between quotes rather than as an int without quotes.

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
user441365
  • 3,934
  • 11
  • 43
  • 62

1 Answers1

6

This requires a custom converter based on Newtonsoft.Json.Converter to be created.

Then you would use the converter like so

[JsonConverter(typeof(ToStringConverter))]
public int StreetCode { get; set; }
ndonohoe
  • 9,320
  • 2
  • 18
  • 25
  • 1
    More info at http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConverter.htm, example implementation here http://stackoverflow.com/questions/22354867/how-to-make-json-net-serializer-to-call-tostring-when-serializing-a-particular – Manfred Radlwimmer Jul 13 '16 at 09:29