How to serialize/deserialize a custom collection with additional properties using Json.Net

The problem is the following: when an object implements IEnumerable, JSON.net identifies it as an array of values and serializes it following the array Json syntax (that does not include properties), e.g. : [ {“FooProperty” : 123}, {“FooProperty” : 456}, {“FooProperty” : 789}] If you want to serialize it keeping the properties, you need to … Read more

ASP.NET MVC: Controlling serialization of property names with JsonResult

I wanted something a bit more baked into the framework than what Jarrett suggested, so here’s what I did: JsonDataContractActionResult: public class JsonDataContractActionResult : ActionResult { public JsonDataContractActionResult(Object data) { this.Data = data; } public Object Data { get; private set; } public override void ExecuteResult(ControllerContext context) { var serializer = new DataContractJsonSerializer(this.Data.GetType()); String output … Read more

How to Serialize Binary Tree

All those articles talk mostly about the serialization part. The deserialization part is slightly tricky to do in one pass. I have implemented an efficient solution for deserialization too. Problem: Serialize and Deserialize a binary tree containing positive numbers. Serialization part: Use 0 to represent null. Serialize to list of integers using preorder traversal. Deserialization … Read more

How to serialize a graph structure?

How do you represent your graph in memory? Basically you have two (good) options: an adjacency list representation an adjacency matrix representation in which the adjacency list representation is best used for a sparse graph, and a matrix representation for the dense graphs. If you used suchs representations then you could serialize those representations instead. … Read more

Gson Serialize field only if not null or not empty

Create your own TypeAdapter public class MyTypeAdapter extends TypeAdapter<TestObject>() { @Override public void write(JsonWriter out, TestObject value) throws IOException { out.beginObject(); if (!Strings.isNullOrEmpty(value.test1)) { out.name(“test1”); out.value(value.test1); } if (!Strings.isNullOrEmpty(value.test2)) { out.name(“test2”); out.value(value.test1); } /* similar check for otherObject */ out.endObject(); } @Override public TestObject read(JsonReader in) throws IOException { // do something similar, but the … Read more