0

I have the following JSON:

{  
    "lastOcurrences":[  
        {  
           "myString":"16726354"
        },
        {  
           "myString":"66728744"
        },
        {  
           "myString":"91135422"
        }
    ]
}

and I have a class to deserialize it on:

public class JsonObject
{
    public List<LastOcurrence> LastOcurrences { get; set; }
}

public class LastOcurrence
{
    public string MyString { get; set; }
}

Upon deserializing it with JsonConvert.DeserializeObject<T>(json), I'd like to be able to format the string myString, to store 167-263-54, instead of 16726354.

What solution would please my soul: Using attributes on the properties, something of the likes of JsonConverter, but...

What i'd like to avoid doing: I would not like to use reflection to iterate through every property, only to then read the attribute and apply the formatting. Is there any way of doing this 'automatically' with JsonConvert?

fhcimolin
  • 616
  • 1
  • 8
  • 27
  • 1
    *something of the likes of `JsonConverter`* - then why not use a [`JsonConverter`](https://www.newtonsoft.com/json/help/html/JsonConverterAttributeProperty.htm)? You can certainly do it it with one of those, see e.g. `StringSanitizingConverter` from [Access custom attributes of .NET class inside custom json converter](https://stackoverflow.com/q/49991050/3744182) or `ReplacingStringConverter` from [running a transformation on a Json DeserializeObject for a property](https://stackoverflow.com/q/38351661/3744182). – dbc Jul 17 '19 at 16:52
  • 1
    @dbc Thanks for pointing out the solution. [This one answer](https://stackoverflow.com/a/38503536/9555272) from the second question you linked did the job neatly well. I'll be closing this question as a duplicate of that one. – fhcimolin Jul 17 '19 at 18:07

1 Answers1

0

One possible solution is to use custom getters and setters for this and when it is deserialized you keep the raw data stored. This will do JIT formatting. Depending on the usage of this data this could be much quicker however if there are a lot of repeated reads of the same data then this may be a bit slower.

public class LastOcurrence
{
    private string _myString;
    public string MyString 
    { 
        get { return Regex.Replace(_myString, @"^(.{ 3})(.{ 3})(.{ 2})$", "$1-$2-$3"); } 
        set { _myString = value; } 
    }
}
Tom Dee
  • 2,516
  • 4
  • 17
  • 25
  • Thanks for the input. That's a valid solution, but I fear having to clutter the object with private properties. – fhcimolin Jul 17 '19 at 16:33