Reputation: 10223
I have a class
public class Person
{
public string Name { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
I'd like to serialize it into:
{ "Person": "[John, Smith, 13]" }
instead of
{"Name":"John", "LastName":"Smith", "Age": 13}
Is it possible to achieve this without writing a custom serializer? If not, how do I apply a custom serializer only to a specific class?
Upvotes: 1
Views: 880
Reputation: 5299
Since the json string you want to get when serializing an instance of Person
is not the standard one, you'll need to write a custom converter and decorate your class with it. One way to do that is the following. Write class that inherits from JsonConverter
:
public class CustomConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null) return;
writer.WriteStartObject();
writer.WritePropertyName(value.GetType().Name);
writer.WriteStartArray();
var properties = value.GetType().GetProperties();
foreach (var property in properties)
writer.WriteValue(value.GetType().GetProperty(property.Name).GetValue(value));
writer.WriteEndArray();
writer.WriteEndObject();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof (Person);
}
}
Decorate your class with the JsonConverter
attribute:
[JsonConverter(typeof(CustomConverter))]
public class Person
{
public string Name { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
Now lets say that you use the following code:
var person = new Person
{
Name = "John",
LastName = "Smith",
Age = 13
};
var json = JsonConvert.SerializeObject(person, Formatting.Indented);
The json
varible wil have this value:
{
"Person": [
"John",
"Smith",
13
]
}
Demo here
Upvotes: 4