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.

4
  • You want to take an existing c# object and serialize it into json? Commented Apr 21, 2017 at 15:15
  • 10
    json2csharp.com if you load an existing json string into this site it will create the classes needed for the C# object. Commented Apr 21, 2017 at 15:15
  • Seems like writing your json manually would be pretty error prone. Why not just serialize a class? Commented Apr 21, 2017 at 15:16
  • Create a class with Name, Children and Size properties and serialize it. Commented Apr 21, 2017 at 15:17

5 Answers 5

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

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
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.

Comments

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.

1 Comment

This would give you something like {"name": "AgglomerativeCluster", "size": 3938, "children": null} which may or may not be a problem for the OP.
1

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

Comments

-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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.