Convert DataTable to JSON with Value only

If I have a datatable in the following structure.

  HostelName FloorName FlatName Occupied Vacant
 Building One Floor AA 2 2
 Building One Floor AB 0 4
 Building One Floor AC 0 4
 Building One Floor AD 0 4
 Building One Floor AE 0 4
 Building One Floor BF 0 4
 Building One Floor BG 0 4
 Building One Floor BH 0 4
 Building One Floor BI 0 4
 Building One Floor BJ 0 4

I would like to serialize it as a JSON object, where the columns HostelName, FloorName and FlatName are nodes in the JSON object, for example:

{ "Building One": { "Floor A": { "A": { "Occupied": "2", "Vacant": "2" }, "B": { "Occupied": "0", "Vacant": "4" }, "C": { "Occupied": "0", "Vacant": "4" }, "D": { "Occupied": "0", "Vacant": "4" }, "E": { "Occupied": "0", "Vacant": "4" } }, "Floor B": { "F": { "Occupied": "0", "Vacant": "4" }, "G": { "Occupied": "0", "Vacant": "4" }, "H": { "Occupied": "0", "Vacant": "4" }, "D": { "Occupied": "0", "Vacant": "4" }, "I": { "Occupied": "0", "Vacant": "4" } } } }; 

Please help me solve the problem.

+5
source share
2 answers

All you have to do is use a custom JSONConverter (if using JSON.NET), find out about it here (JSON.NET Implementing custom serialization) .

+1
source

If there are no finite number of rooms on each floor, I would make the rooms massive. The same goes for floors. It makes more sense, and it’s easier to work with if you are going to disassemble it later.

To write custom JSON, you can use JSON.net JsonWriter . Then you can write it like this:

 StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); using (JsonWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.Indented; writer.WriteStartObject(); writer.WritePropertyName("Building One"); writer.WriteStartObject(); writer.WritePropertyName("Floor A"); writer.WriteStartObject(); writer.WritePropertyName("A"); writer.WriteStartObject(); writer.WritePropertyName("Occupied"); writer.WriteValue("2"); writer.WritePropertyName("Vacant"); writer.WriteValue("2"); writer.WriteEnd(); writer.WritePropertyName("B"); writer.WriteStartObject(); writer.WritePropertyName("Occupied"); writer.WriteValue("0"); writer.WritePropertyName("Vacant"); writer.WriteValue("4"); writer.WriteEnd(); writer.WriteEndObject(); } 

Or using JTokens

 JObject o = new JObject( new JProperty("Building One", new JObject( new JProperty("Floor A", new JObject( new JProperty("A", new JObject( new JProperty("Occupied", "2"), new JProperty("Vacant", "2"))), new JProperty("B", new JObject( new JProperty("Occupied", "0"), new JProperty("Vacant", "4")))))))); 
0
source

All Articles