1

I thought this would pretty easily to convert from JSON array to a comma-separated string and back using Newtonsoft, but I am having issues getting the ReadJson to work. I thought I would just deserialize from the reader to a string array and then call Join, but I keep getting errors: Unexpected token while deserializing object: PropertyName. Path '[0]..

Here is the code I am using:

public class myModel
{
    [JsonConverter(typeof(CommaSeperatedStringJsonConverter))]
    public string myString { get; set; }
    public int myNumber { get; set; }
}

public class CommaSeperatedStringJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var stringArray = serializer.Deserialize(reader, typeof(string[]));
        return string.Join(",", stringArray);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is null)
        {
            writer.WriteNull();
        } 
        else
        {
            serializer.Serialize(writer, value.ToString().Split(','), typeof(string[]));
        }
    }
}

1 Answer 1

2

Try using the generic version of Deserialize instead. In other words, change this line:

var stringArray = serializer.Deserialize(reader, typeof(string[]));

To this:

var stringArray = serializer.Deserialize<string[]>(reader);

Fiddle: https://dotnetfiddle.net/KpQSiG

It shouldn't matter, but for some reason it does in this situation. If I have more time I'll try to dig into the source code to see what is happening.

Sign up to request clarification or add additional context in comments.

2 Comments

Turns out I had a bug a different custom Json Converter being used on the same class, that was executing before this one. I am still using .Net Framework and NetwonSoft 12.03, your example looks to be using .Net Core.
I updated the fiddle to use .Net Framework 4.7.2 instead of .Net Core. The solution still seems to work.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.