Reputation: 747
I have an external data contract, which cannot be modified. Json is used to serialize these classes. I need to save on output data size, so I would like to change original fields names to their shorter versions, i.e.:
public ClassWithLongName
{
public string FieldWithLongName = "field1";
public string FieldWithEvenLongerName = "field2";
}
should be serialzed to something like:
{"f1" = "field1", "f2" = "field2"}
To have ability to deserialize it back properly, mapping between original and short names must be provided somehow (I was thinking about dictionary. Should I use CustomConverter or IContractResolver for that?
EDIT:
There is a way to do it using CustomContractResolver : DefaultContractResolver. I am overriding CreateProperty method to swap the property name. A the moment the problem is that I can't get serialized object type (so all the properties' names are being held in one common map, instead of separate maps per type). Do you know how can I get serialized object type from DefaultContractResolver?
EDIT2:
The type can be taken from ResolveContract method (it is passed as parameter here). I have achieved the functionality I needed, but there is one huge problem with it. Performance. I counted time elapsed fo serializing simple object 10000 times in a loop. For default serialization it was about 150ms and for custom serialization about 15s. Do you know if there is a way to avoid it. I suppose that the overhead is caused by reflection. But how can default serializer avoid it? I am using DefaultContractResolver as parent class for my CustomContractResolver, so it should use all the mechanisms that parent class is using..
Upvotes: 0
Views: 1001
Reputation: 8166
If you didn't want to use anonymous objects, you could create your own object and use AutoMapper
to map the external data contract into your own class and then serialize that using JavaScriptSerializer
classes
Upvotes: 1
Reputation:
Use anonymouse object:
ClassWithLongName obj = new ClassWithLongName();
var anonymouse = new { FieldWithLongName = obj.FieldWithEvenLongerName, FieldWithEvenLongerName = obj.FieldWithEvenLongerName };
JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(anonymouse);
Upvotes: 1