c#


Generic method to convert a flat JSON array to nested JSON


I have a JSON object as below
[
{
"Id": 7,
"Name": "Colocation Folder",
"ParentId": 1,
"depth": 0
},
{
"Id": 8,
"Name": "CoLo Real Estate",
"ParentId": 7,
"depth": 1
},
{
"Id": 10,
"Name": "CoLo: Burst",
"ParentId": 7,
"depth": 1
},
{
"Id": 34,
"Name": "CoLo Dedicated Bandwidth",
"ParentId": 7,
"depth": 1
},
{
"Id": 10035,
"Name": "Infrastructure as a Service",
"ParentId": 7,
"depth": 1
},
{
"Id": 10037,
"Name": "Software as a Service",
"ParentId": 7,
"depth": 1
},
{
"Id": 10038,
"Name": "IaaS Component Upgrade",
"ParentId": 7,
"depth": 1
},
{
"Id": 668,
"Name": "CoLo Misc Folder",
"ParentId": 7,
"depth": 1
},
{
"Id": 758,
"Name": "CoLo: Conduit Fee",
"ParentId": 668,
"depth": 2
},
{
"Id": 765,
"Name": "CoLo: Private VLAN",
"ParentId": 668,
"depth": 2
}
]
The Id and ParentId fields show the relation between the items. I need to make it as a nested JSON using C#.
Since there will be many such models, I don't want to create individual classes for each model. Is there a generic approach in C# that will take a flat JSON array, take the ID and ParentId fields as input and then return me a nested JSON with all other fields in the array as well? For example, I am looking for an output of nested JSON as below:
[
{
"Id": 7,
"Name": "Colocation Folder",
"items": [
{
"Id": 8,
"Name": "CoLo Real Estate",
"ParentId": 7
},
{
"Id": 10,
"Name": "CoLo: Burst",
"ParentId": 7
},
{
"Id": 34,
"Name": "CoLo Dedicated Bandwidth",
"ParentId": 7
},
{
"Id": 10035,
"Name": "Infrastructure as a Service",
"ParentId": 7
},
{
"Id": 10037,
"Name": "Software as a Service",
"ParentId": 7
},
{
"Id": 10038,
"Name": "IaaS Component Upgrade",
"ParentId": 7
},
{
"Id": 668,
"Name": "CoLo Misc Folder",
"ParentId": 7,
"items": [
{
"Id": 758,
"Name": "CoLo: Conduit Fee",
"ParentId": 668
},
{
"Id": 765,
"Name": "CoLo: Private VLAN",
"ParentId": 668
}
]
}
]
}
]
If you use Json.Net, you can do this conversion in a generic way using the LINQ-to-JSON API (JObjects). The idea is to parse the JSON array and add all the individual items to a dictionary keyed by Id. Then, loop over the dictionary items, and for each one, try to look up the parent. If the parent is found, add the item to the parent's items array (creating it if needed). Otherwise, add the item to the root array. Along the way, remove the depth property from each item, since you don't seem to want that in the output. Lastly, just dump the root array to string to get the final result.
var dict = JArray.Parse(json)
.Children<JObject>()
.ToDictionary(jo => (string)jo["Id"], jo => new JObject(jo));
var root = new JArray();
foreach (JObject obj in dict.Values)
{
JObject parent;
string parentId = (string)obj["ParentId"];
if (parentId != null && dict.TryGetValue(parentId, out parent))
{
JArray items = (JArray)parent["items"];
if (items == null)
{
items = new JArray();
parent.Add("items", items);
}
items.Add(obj);
}
else
{
root.Add(obj);
}
JProperty depth = obj.Property("depth");
if (depth != null) depth.Remove();
}
Console.WriteLine(root.ToString());
Fiddle: https://dotnetfiddle.net/Buza6T
You can use a dynamic object with JSON.Net like so to detect your properties dynamically then you could build a new json object with the desired nesting:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
dynamic d = JArray.Parse(stringy);
foreach(var ob in d)
{
if(ob.ParentID != ob.Id)
{
string debug = "oh snapple, it's a child object";
}
}

Related Links

How to unbind a concrete self-bound singleton binding in Ninject 3?
Displaying code with numbered code lines
want to set image url in listview from a function return in asp.net
How can I create an IEnumerable from an enum [duplicate]
How can I debug a 500 Internal Server Error when calling a WebApi from ajax?
Fileupload control display [closed]
XNA Deferred Shader, Replace BasicEffect
Extracting value from string
Data integrity in Entity Framework
Unable to bind a ResourceDictionary item to Rectangle.Child
What are masked assertions in Microsoft Code Contracts? [duplicate]
c# webservice receive complex array [closed]
dynamically change checkbox background\foreground-color which is inside an itemtemplate inside gridview
How do I create XML with namespace prefixes?
To refresh a listview in a form from a button click in another form
How to integrate Facebook like button to our asp.net c# website

Categories

HOME
logging
sip
postgresql-9.3
popover
file-upload
hex
cryengine
lithium
assign
pandoc
sms
yuv
rethinkdb
vsixmanifest
sahi
soap-client
runtime
velocity
logstash-configuration
yui
hql
dompdf
sonarlint
ajaxcontroltoolkit
matlab-gui
devexpress-mvc
my.cnf
oracle10g
traveling-salesman
mongoose-im
cloudformation
checkmarx
sphinx4
boost-log
flickr
libconfig
jquery-inputmask
jslider
aura-framework
pyexcel
smooth-streaming
servicebus
android-doze-and-standby
mef
hierarchical-clustering
jcs
openidm
extjs3
runtime-permissions
openpgp.js
sp
business-catalyst
bipartite
trusted-computing
spring-cloud-aws
mavlink
strtol
git-push
kik
avi
supervised-learning
salesforce-service-cloud
wordpress-plugin
fadein
askbot
wonderware
ewam
php-gd
tooltwist
stereotype
cakephp-2.6
tidesdk
pymol
nexusdb
touch-typing
cordova-3
iphone-6
serializer
xpand
smartxls
email-headers
cvi
data-layers
php-amqplib
thucydides
ironworker
objectdatasource
oc4j
latex-suite
metapost
cron4j
yii-components
databus
php-gettext
win-prolog
pinchzoom
idtabs
apache-commons-email
mscorlib
virtual-printer
discussion-board
isgl3d
soapexception
onunload
iphone-maps
silverlight-2.0
cross-cutting-concerns
moores-law
ironpython-studio

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App