如何使用C#创建复杂的JSON对象

时间:2017-04-21 15:14:28

标签: c# json

我有这样的JSON结构:

{
 "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}
   ]
  }
 ]
}

如何使用C#生成这样的JSON,我发现了如何制作JSON数组,但这就是我所拥有的。我不知道如何制作children":属性,或者我不知道如何制作一个由其他JSON对象或其他JSON数组组成的JSON对象。你可以给我一点提升,以便我可以生成这样的JSON对象吗?谢谢。

5 个答案:

答案 0 :(得分:3)

根据需要定义您的类:

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

然后使用Newtonsoft,Json.NET或任何其他库将其作为JSON。

答案 1 :(得分:3)

如果你使用Json.Net(你应该),你可以创建一个这样的类:

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

然后,如果你像这样创建你的对象(我不做整个事情,只是几个级别 - 显然你没有一次填充它):< / p>

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

然后:

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

哪会给你(为了可读性而格式化):

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

几点说明:

NullValueHandling = NullValueHandling.Ignore可以禁止包含值为null的属性。如果您不关心Name = "flare"size: null的对象,那么您无需担心它。但是,如果你这样做,使用它可以节省至少三个不同的对象,这些对象大致相同但缺少一些属性。

CamelCasePropertyNamesContractResolver会自动骆驼你的财产名称。您可以将MyObject中的属性设置为驼峰,但这不是.NET标准。如果你可以打破这个约定,那么你就不需要了。另一种方法是在每个.NET属性的PropertyName中设置JsonPropertyAttribute

答案 2 :(得分:2)

使用匿名类型,您可以使用普通JSON定义对象层次结构。然后使用Json.Net序列化它:

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

对于更复杂的层次结构,您可能需要涉及动态类型。这是您的原始对象:

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

演示:https://dotnetfiddle.net/u2HIt3

答案 3 :(得分:1)

您可以使用Json.NET序列化/反序列化复杂对象。

答案 4 :(得分:-1)

您可以做很多事情,但是我发现的一种简单方法就是这样

  1. 创建您的大师班
  2. 创建您的Child类
  3. 让主人和孩子充满
  4. 按如下所示获取JSON
  5. 如果需要传递child_detail列表以获取子对象的数组,您将看到预期的JSON。
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);