Deserialize List<string> from Json to List<object>
You are going to have to write a converter for the UserGroup
Here is a simple converter based on what was described in the question
public class UserGroupJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(UserGroup) == objectType; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return new UserGroup((string)reader.Value); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(((UserGroup)value).Code); }}
And then update the User
to be aware of the converter by setting the ItemConverterType
of the JsonProperty
attribute
[JsonObject(MemberSerialization.OptIn)]public class User { public User(string code) { this.Code = code; } [JsonProperty] public string Code { get; set; } private List<UserGroup> groups; [JsonProperty("Groups", ItemConverterType = typeof(UserGroupJsonConverter))] public List<UserGroup> Groups { get { if (groups == null) groups = new List<UserGroup>(); return groups; } }}
This would now allow for the JSON in the example
{ "Code": "Admin", "Groups": [ "Administrator", "Superuser", "User" ]}
to be deserialized as desired
var user = JsonConvert.DeserializeObject<User>(json);
and to be serialized back into the same format.
var json = JsonConvert.SerializeObject(user);
Administrator is a string, UserGroup is an object so this is a type mismatch. The valid JSON for the scenario laid out in your code is:
{ "Code": "Admin", "Groups": [ { "Code":"Administrator" }, { "Code":"Superuser" }, { "Code":"User" } ]}