I wonder if it is possible to serialize and deserialize any List<string> as a string of comma separated values in C# using Json.Net:
class MyDTO
{
public int Age { get; set; } = 25;
public string Name { get; set; } = "Jon";
public List<string> Friends { get; set; } = new List<string> {"Jan", "Joe", "Tim"};
}
var serilalized = JsonConvert.SerializeObject(new MyDTO());
//serialized = { "name": "Jon", "age": 25, "friends": "Jan,Joe,Tim" }
var deserialized = JsonConvert.DeserializeObject<MyDTO>(serialized);
//deserialized.Name = "Jon", deserialized.Age = 25, deserialized.Friends = List<string> {"Jan", "Joe", "Tim"}
How could I achieve what the comments in the code reflect?
Implementing a custom JsonConverter is a good solution to this problem, but when I deserialize using the non generic version JsonConvert.DeserializeObject(serialized), the JsonConverter does not have effect and the deserialized value has type JTokenType.String, instead of JTokenType.Array that is the type that I want to get. For example:
JObject obj = (JObject)JsonConvert.DeserializeObject(serilalized);
JToken token = obj["friends"];
Console.WriteLine(token.Type == JTokenType.String); //prints true
Console.WriteLine(token.Type == JTokenType.Array); //prints false
I would like that the code above could print false in the first case and true in the second. Note that while deserializating I don't have the type MyDTO available.
{age: 25, name: "Jon", friends = "\"Jan\", \"Joe\", \"Tim\""}that's not valid json, so no.{age: 25, name: "Jon", friends: ["Jan", "Joe", "Tim"] }? (in other words, did you try it and look at what it generated?)"[\"Jan\",\"Joe\",\"Tim\"]"is a string not a json array. I added the last comment of the question trying to avoid this confusion.