Saturday, December 29, 2018

c# - (De-)Serialize Known Types similar to Microsoft

Up to now I've used Microsoft's DataContractJsonSerializer to serialize and deserialize my business objects into data transfer objects (DTO) formatted as JSON.
The DTOs are marked with the DataContract attribute. A small example:



[DataContract(Name = "Geometry", Namespace = "myContract.com/dto")]
[KnownType(typeof(Point))]
[KnownType(typeof(Line))]
public class Geometry
{

}

[DataContract(Name = "Point", Namespace = "myContract.com/dto")]
public class Point : Geometry
{
[DataMember(Name = "x")]
public double X { get; set; }

[DataMember(Name = "y")]
public double Y { get; set; }

}

[DataContract(Name = "Line", Namespace = "myContract.com/dto")]
public class Line: Geometry
{
[DataMember(Name = "start")]
public Point Start { get; set; }

[DataMember(Name = "end")]
public Point End { get; set; }

}


This gets serialized as:



"geometry":{"__type":"Point:myContract.com/dto","x":23133.75569999963,"y":21582.385849999264}


Because of performance issues I switched to Newtonsoft Json.NET. When using this, the JSON strings looks like this:




"geometry":{"$type":"A.B.C.Point, A.B.C","x":23133.75569999963,"y":21582.385849999264}


Is there are possibility to serialize the object with Json.NET into a Microsoft-conform JSON string using "__type" and the contract namespace instead of "$type" and the class-assembly-combination?
I'm using .NET 3.5.



Thanks in advance!

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...