jason
jason

Reputation: 7164

How to create a complex JSON object using C#

I have such a JSON structure :

{
 "name": "flare",
 "children": [
  {
   "name": "analytics",
   "children": [
    {
     "name": "cluster",
     "children": [
      {"name": "AgglomerativeCluster", "size": 3938},
      {"name": "MergeEdge", "size": 743}
     ]
    },
    {
     "name": "graph",
     "children": [
      {"name": "BetweennessCentrality", "size": 3534},
      {"name": "SpanningTree", "size": 3416}
     ]
    },
    {
     "name": "optimization",
     "children": [
      {"name": "AspectRatioBanker", "size": 7074}
     ]
    }
   ]
  },
  {
   "name": "animate",
   "children": [
    {"name": "Easing", "size": 17010},
    {"name": "FunctionSequence", "size": 5842},
    {
     "name": "interpolate",
     "children": [
      {"name": "ArrayInterpolator", "size": 1983},
      {"name": "RectangleInterpolator", "size": 2042}
     ]
    },
    {"name": "ISchedulable", "size": 1041},
    {"name": "Tween", "size": 6006}
   ]
  }
 ]
}

How can I generate such a JSON using C#, I found out how to make a JSON array but that's all I have. I don't know how to make children": attribute or I don't know how to make a JSON object that consists of other JSON objects or other JSON arrays. Can you give me a little boost so that I can generate such a JSON object? Thanks.

Upvotes: 2

Views: 18550

Answers (5)

Shailesh Tiwari
Shailesh Tiwari

Reputation: 335

You can do many ways however one of the easy way I found is like this

  1. Create your Master class
  2. Create your Child class
  3. Fill master and child
  4. Get your JSON as below
  5. You will see your expected JSON if required pass List of child_detail to get array of your child object.
public class master_header
{
    public string name{ get; set; }
    public string hdrdetail { get; set; }
}

public class child_detail
{
    public string childname { get; set; }
    public string chdetail { get; set; }
}
var myjson = new
{
    master_header= master_header,
    child_detail= child_detail
};
var jsonContent = JsonConvert.SerializeObject(myjson);

Upvotes: -1

Dmitry Egorov
Dmitry Egorov

Reputation: 9650

With anonymous types you may define an object hierarchy almost as easy as with plain JSON. Then just serialize it using Json.Net:

var obj = new {
    name = "flare",
    children = new[] {
        new { name = "analytics" },
        new { name = "animate" },
    }
};
var json = JsonConvert.SerializeObject(obj, Formatting.Indented);

For more complex hierarchies you may need to involve dynamic types. Here is your original object:

var obj = new {
    name = "flare",
    children = new[] {
        new {
            name = "analytics",
            children = new dynamic [] {
                new {
                    name = "cluster",
                    children = new dynamic [] {
                        new { name = "AgglomerativeCluster", size = 3938},
                        new { name = "MergeEdge", size = 743},
                    }
                },
                new {
                    name = "graph",
                    children = new dynamic [] {
                        new { name = "BetweennessCentrality", size = 3534},
                        new { name = "SpanningTree", size = 3416},
                    }
                },
                new {
                    name = "optimization",
                    children = new dynamic [] {
                        new { name = "AspectRatioBanker", size = 7074},
                    }
                },
            }
        },
        new {
            name = "animate",
            children = new dynamic [] {
                new { name = "Easing", size = 17010},
                new { name = "FunctionSequence", size = 5842},
                new {
                    name = "interpolate",
                    children = new [] {
                    new { name = "ArrayInterpolator",  size = 1983},
                    new { name = "RectangleInterpolator", size = 2042}
                    }
                },
                new { name = "ISchedulable", size = 1041},
                new { name = "Tween", size = 6006},
            }
        },
    }
};
var json = JsonConvert.SerializeObject(obj, Formatting.Indented);

Demo: https://dotnetfiddle.net/u2HIt3

Upvotes: 6

Matt Burland
Matt Burland

Reputation: 45135

If you use Json.Net (and you should), you can create a class like this:

public class MyObject
{   
    public string Name { get; set; }
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public List<MyObject> Children { get; set; }
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public int? Size { get; set; }
}

Then if you create your object like this (and I'm not doing the whole thing, just a few levels - and obviously you don't have to populate it all at once):

var root = new MyObject() 
{
    Name = "flare",
    Children = new List<MyObject>() 
    {
        new MyObject()
        {
            Name = "analytics",
            Children = new List<MyObject>() 
            {
                new MyObject()
                {
                    Name = "cluster",
                    Children = new List<MyObject>() 
                    {
                        new MyObject() { Name = "AgglomerativeCluster", Size = 3938 }
                    }
                }
            }
        }
    }
};

And then:

var json = JsonConvert.SerializeObject(root, new JsonSerializerSettings 
{ 
    ContractResolver = new CamelCasePropertyNamesContractResolver()
}));

Which would give you (formatted after the fact for readability):

{
    "name": "flare",
    "children": [{
        "name": "analytics",
        "children": [{
            "name": "cluster",
            "children": [{
                "name": "AgglomerativeCluster",
                "size": 3938
            }]
        }]
    }]
}

A couple of notes:

NullValueHandling = NullValueHandling.Ignore lets you suppress the inclusion of properties where the values are null. If you don't care about the object with Name = "flare" have a size: null, then you don't need to worry about it. But if you do, using it saves you have at least three different objects that are largely the same but missing some properties.

CamelCasePropertyNamesContractResolver will automatically camel case your property names. You could just make the properties in MyObject be camel cased, but that's not the .NET standard. If you are okay with breaking that convention, then you don't need it. Another alternative would be to set PropertyName in the JsonPropertyAttribute for each .NET property.

Upvotes: 5

Vicen&#231; Gasc&#243;
Vicen&#231; Gasc&#243;

Reputation: 1346

Define your classes as required:

public class Human
{
  public string name { get; set; }
  public int size { get; set; }
  public IEnumerable<Human> children { get; set; }
}

Then use Newtonsoft, Json.NET or any other library to get it as JSON.

Upvotes: 4

Uladzimir Palekh
Uladzimir Palekh

Reputation: 1871

You can use Json.NET to serialize/deserialize complex objects.

Upvotes: 1

Related Questions