Serializing attributes on member

Dec 13, 2012 at 3:10 PM

Hello,

i have been trying to serialize the attributes present on the member of a class to JSON. For example:

class Test {

	[Required]

	[MaxLength(Length=5)]

	public string A { get; set; }



	[MinLength(Length=3)]

	public string B { get; set }

}

should be serialize to JSON :

{

	A : "the value of string A",

	B : "the value of string B",

	$_attributes: {

		A: {

			required: true,

			maxLength: { Length: 5 }

		},

		B: {

			minLength: { Length: 3 }

		}

	}

}

My goal is to serialize my view-model attributes, and rehydrate them on the javascript side using knockout and knockout-validation.

I have been trying to achieve this using JSON.NET and by implementing a ContractResolver (which inherits the DefaultContractResolver). My contract resolver should inspect each property of a type and if any attribute are present, generate a supplementary JsonProperty "$_attributes" containing all the infos of each attributes.

Does someone have any clues or advices on a better way to do this ?