1

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?

1
  • 2
    you can try {"Person" : ["John","Smith",13]}. Commented Sep 10, 2014 at 12:34

1 Answer 1

4

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

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

Comments

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.