Radu Ungureanu
Radu Ungureanu

Reputation: 131

Custom object serialization

Is there a way to change how an object is serialized in json? for example, the following object:

class PersonName {
  public string Name { get; set; }
}

var obj = new { 
    pName = new PersonName { 
        Name = "Andrew"
    }
}

is serialized as {"pName": { "name": "Andrew" }}.

But is there a way to serialize it as {"pName": "Andrew"}?

Upvotes: 0

Views: 79

Answers (2)

Radu Ungureanu
Radu Ungureanu

Reputation: 131

So finally I've managed to get the answer to this one.

A custom converter is needed:

public class PersonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var person = value as PersonName;
        if (person == null)
        {
            return;
        }
        serializer.Serialize(writer, person.Name);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var constructorInfo = objectType.GetTypeInfo().GetConstructors(BindingFlags.Public | BindingFlags.Instance).Single();
        var parameterInfo = constructorInfo.GetParameters().Single();
        var parameterType = parameterInfo.ParameterType;

        var value = serializer.Deserialize(reader, parameterType);
        return Activator.CreateInstance(objectType, new[] { value });
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(PersonName).GetTypeInfo().IsAssignableFrom(objectType);
    }
}

which can be used like this:

[JsonConverter(typeof(PersonConverter))]
public class PersonName
{
    public PersonName(string name)
    {
        Name = name;
    }

    public string Name { get; set; }
}

Upvotes: 0

sebsch
sebsch

Reputation: 131

This should work:

class PersonName 
{
    [JsonProperty(PropertyName = "pName")]
    public string Name { get; set; }
}
var obj = new  PersonName { Name = "Andrew" }

Upvotes: 1

Related Questions