2

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.

jason
  • 6,962
  • 36
  • 117
  • 198

5 Answers5

6

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

Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40
  • this is amazing solution. It helped me to easily get a huge body required for POST call. Thanks a lot this is time saving solution for those who need to create complex json payload and serialize to use it in C# API call. Thanks a ton – kjosh Apr 07 '20 at 03:23
5

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.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
4

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.

Jodrell
  • 34,946
  • 5
  • 87
  • 124
Vicenç Gascó
  • 1,326
  • 2
  • 13
  • 21
  • This would give you something like `{"name": "AgglomerativeCluster", "size": 3938, "children": null}` which may or may not be a problem for the OP. – Matt Burland Apr 21 '17 at 15:54
1

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

Uladzimir Palekh
  • 1,846
  • 13
  • 16
-1

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);
Cleptus
  • 3,446
  • 4
  • 28
  • 34
Shailesh Tiwari
  • 295
  • 4
  • 4