I want to implement a custom JsonConverter to use as such,
[JsonConverter(typeof(ArrayString))]
public string ServiceCodes { get; set; }
The purpose is to convert a JSON array to a string with separators, e.g.,
["this", "is", "my", "json", "array"]
should become "this;is;my;json;array"
(or whatever separator). Likewise, the reverse should be possible.
I struggle to understand overriding the WriteJson
method of JsonConverter
.
To provide some context, I ServiceCodes
is a property on an Entity (I'm using EF6). I think it's easier to do what I'm asking for my case than other one to many implementations. One question I have, however, is when is the JsonConverter called?
I only want the the get
to give json when the getter desires json, namely, when the object which contains this property is being return as JSON from my API. I don't want this converter to called when I'm writing LINQ, for example.
Any help would be appreciated, thank you.
EDIT - info added
Here's the class and some moc data.
[ComplexType]
public class TerminalDuties
{
public string TerminalCode { get; set; }
public string TransportationCode { get; set; }
[JsonConverter(typeof(ArrayString))]
public string ServiceCodes { get; set; }
}
"Origin": {
"TerminalCode": "MIA",
"TransportationCode": "GT",
"ServiceCodes": ["WH", "HL"]
}
I tried @felix-b's answer, but it was not mapping. The object was null. I had breakpoints in the ArrayString class but they were not hit. Presumably it did not try to map because the property is a string. What is the workaround?
Here's how it's exposed in my Web API Controller (inherits from ApiController)
[HttpPost]
public void DoStuff([FromBody]Thing t)
{
someMngr.Add(t);
}
public class Thing : ParentClass
{
properties...
public TerminalDuties Origin { get; set; }
}
"this;is;an;array"
to["this", "is", "an", "array"]
, you may have to write a custom converter to do it (perhaps just a simplestring.Split
..?). TheJsonConverter
attribute is only used when a Json serializer is being used to convert the object. Start out with understanding what web framework you are using - ASP.NET MVC, ASP.NET Web API etc.? And then narrow down your search on how to serialize the response from your API methods.