This project has moved. For the latest updates, please go here.

Trying to deserialize comma-separated value string - getting exception

Feb 3, 2012 at 6:21 PM

I'm trying to use an external API that returns some data as a comma-separated string of integers.  I added an int[] property to my class and wrote a custom converter to parse the comma separated string in to an int array.  When I run my code, though I get an error that 

"JsonConverter CellControlSpeedConverter on Int32[] Observations is not compatible with member type Int32[]"

Here's my member declaration: (code snippet tool is not working for me in any browser, sorry)

[JsonProperty(PropertyName = "speed-list")]
int[] Observations { get; set; }


Here's my JsonConverter ReadJson: (omitted other methods for brevity, please ignore the overly pedantic syntax, was trying anything to get this working)

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)

            if (reader.TokenType == JsonToken.String)

            throw new ArgumentException(String.Format("Unexpected token parsing speed observations. Expected String, got {0}.", reader.TokenType));

            string delimitedObservations = reader.Value.ToString().Trim();
            char[] delimiter = new char[1] { ',' };
            string[] observations = delimitedObservations.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);

            int[] output = new int[observations.Length];

            for (int sequence = 1; sequence <= observations.Length; sequence++)
                string observation = observations[sequence - 1];
                int speed = 0;
                if (int.TryParse(observation, out speed))
                    output[sequence - 1] = speed;
                    throw new ArgumentException(String.Format("Unexpected speed value parsing speed observations. Expected Int, got {0}", observation));

            return output;





Feb 6, 2012 at 5:41 PM


OK, I figured out my own problem after I installed the Json.NET source code and stepped through it.

The issue was that the class that inherits from JsonConverter (in my caseCellControlSpeedConverter) must implement a method called CanConvert that tells the Json Serializer whether or not your custom converter can perform the requested conversion. The input variable is Type objectType. The documentation is silent on what the purpose of this variable is.

I had assumed (based mostly on the method name) that this variable represented the type of the INPUT object (that is, the source object that you are trying to convert FROM). It turns out that this method is actually passed the DESTINATION object type.

So in my example above, my CanConvert method was returning true if passed a string and false otherwise. To get the conversion working I changed that method so that it returned true when passed int[] instead.