这是我设计的json类,包含标题和细节,我使用的是Visual Studio 2015
public class SubDetail
{
public string Sub1 { get; set; }
public string Sub2 { get; set; }
public string Sub3 { get; set; }
}
public class RootObject
{
public string No { get; set; }
public int Age { get; set; }
public List<SubDetail> SubDetail { get; set; }
}
以及如何使用linq编写c#代码并将json输出如下所示
[
{
"No":"1",
"Age":7,
"SubDetail":
[
{
"Sub1":"1",
"Sub2":"2",
"Sub3":"3"
},
{
"Sub1":"4",
"Sub2":"5",
"Sub3":"6"
},
{
"Sub1":"7",
"Sub2":"8",
"Sub3":"9"
}
]
}
]
答案 0 :(得分:3)
有许多库可以将对象图序列化为JSON格式。最受欢迎且易于使用的是Newtonsoft JSON.NET,它允许您使用一行轻松生成JSON:
inst/
这与LINQ无关,主要是因为您无需探索SubDetail集合并手动生成JSON。使用标准的,已接受的测试解决方案。
答案 1 :(得分:1)
public class SubDetail
{
public string Sub1 { get; set; }
public string Sub2 { get; set; }
public string Sub3 { get; set; }
}
public class RootObject
{
public string No { get; set; }
public int Age { get; set; }
public List<SubDetail> SubDetail { get; set; }
}
class Program
{
static void Main(string[] args)
{
RootObject obj = new RootObject();
obj.No = "1";
obj.Age = 7;
int lenght = 3;
int counter = 0;
for(int i=0; i<lenght; i++)
{
SubDetail detail = new SubDetail();
detail.Sub1 = (counter + 1).ToString();
detail.Sub2 = (counter + 1).ToString();
detail.Sub3 = (counter + 1).ToString();
if (obj.SubDetail == null)
obj.SubDetail = new List<SubDetail>();
obj.SubDetail.Add(detail);
}
var jsonString = JsonConvert.SerializeObject(obj);
Console.WriteLine(jsonString);
}
}
以下是您案例的完整示例。此外,您需要将Newtonsoft.Json dll添加到您的项目中,您可以在程序包管理器控制台中使用此行。
Install-Package Newtonsoft.Json -Version 7.0.1