0

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; }
    }
5
  • If you are looking to convert from "this;is;an;array" to ["this", "is", "an", "array"], you may have to write a custom converter to do it (perhaps just a simple string.Split..?). The JsonConverter 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. Commented Nov 17, 2017 at 20:12
  • Thank you, @GeoffJames! I am in ASP.NET Web API 2 right now. Yes, I am planning to implement using string.Split and string.Join. My head is just full trying to do it in the JsonConverter methods.
    – brnis
    Commented Nov 17, 2017 at 20:50
  • No worries. I would take it one step at a time. Strip it back to where you began (before the attribute etc.), and first get it returning Json in the requests. Then, when you're sure that's working, you can get to work on your custom converter. Otherwise you're trying to solve many problems at once, and can't always be sure of the cause/effect of what you just changed etc. Commented Nov 17, 2017 at 20:56
  • [JsonConverter(typeof(ArrayString))] is incorrect; please use [JsonConverter(typeof(ArrayString), ';')] instead. Since you mentioned "whatever separator" in the question, I made it configurable.
    – felix-b
    Commented Nov 17, 2017 at 22:20
  • Changed the answer so that [JsonConverter(typeof(ArrayString))] now works as well, using semicolon as default delimiter.
    – felix-b
    Commented Nov 17, 2017 at 22:30

1 Answer 1

5

Tested with .NET Framework 4.6.1, ASP.NET Web API 2, Entity Framework 6.1.3, Newtonsoft.Json 10.0.3.

UPDATE

My answer originally required [JsonConverter(typeof(ArrayString), ';')] to be specified, as opposed to [JsonConverter(typeof(ArrayString))] in the question.

I added default constructor to the converter class, so that delimiter configuration is optional, and semicolon will be used if not specified. Now [JsonConverter(typeof(ArrayString))] works either.

ORIGINAL ANSWER

The converter will only be invoked during serialization and deserialization of your entity through JSON.NET. It doesn't influence getting or setting property value from code, neither LINQ queries and DB operations.

Here is converter implementation:

public class ArrayString : JsonConverter
{
    private readonly char _delimiter;

    // UPDATE -- added default constructor, so that 
    // JsonConverter attribute can be specified without the 
    // delimiter parameter, in which case semicolon will be used
    public ArrayString() : this(';')
    {
    }

    public ArrayString(char delimiter)
    {
        _delimiter = delimiter;
    }

    public override bool CanRead => true;
    public override bool CanWrite => true;

    public override bool CanConvert(Type objectType)
    {
        return true; 
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType != JsonToken.StartArray)
        {
            return null;
        }

        var stringValue = new StringBuilder();

        while (reader.Read() && reader.TokenType == JsonToken.String)
        {
            if (stringValue.Length > 0)
            {
                stringValue.Append(_delimiter);
            }
            stringValue.Append((string)reader.Value);
        }

        return stringValue.ToString();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var stringValue = value?.ToString();

        if (stringValue == null)
        {
            writer.WriteNull();
            return;
        }

        var arrayValue = stringValue.Split(_delimiter);

        writer.WriteStartArray();

        foreach (var item in arrayValue)
        {
            writer.WriteValue(item);
        }

        writer.WriteEndArray();
    }
}

Here is how you can specify a delimiter character (semicolon in this example):

[JsonConverter(typeof(ArrayString), ';')]
public string ServiceCodes { get; set; }
10
  • Thank you so much, @felix-b! I was just scraping through the documentation at www.newtonsoftjson.com and scratching my head. You're the best!
    – brnis
    Commented Nov 17, 2017 at 21:09
  • *newtonsoft.com/json
    – brnis
    Commented Nov 17, 2017 at 21:32
  • Upon POSTing, it does not map a JSON array to the property. I guess I would have to implement a custom mapper. Would that be the right direction?
    – brnis
    Commented Nov 17, 2017 at 21:39
  • In my tests I did JsonConvert.SerializeObject and JsonConvert.PopulateObject on an EF6 entity. Let me know how you expose your API (ASP.NET MVC? OData? which versions?) and I will try to reproduce
    – felix-b
    Commented Nov 17, 2017 at 21:50
  • I am using ASP.NET Web API 2.
    – brnis
    Commented Nov 17, 2017 at 21:53

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.