如何从标题和详细信息类创建Json [英] How to create Json from header and detail class

查看:76
本文介绍了如何从标题和详细信息类创建Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我设计的json类,包含标题和详细信息,并且我正在使用Visual Studio 2015

This is json class that I was design and contain header and also detail, and I'm using 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

and How to write c# code by using linq and get json out put like below

[
 {  
    "No":"1",
    "Age":7,
    "SubDetail":            
    [
    {   
      "Sub1":"1",
    "Sub2":"2",
    "Sub3":"3"
    },
    {
    "Sub1":"4",
    "Sub2":"5",
    "Sub3":"6"
    },
              { 
    "Sub1":"7",
    "Sub2":"8",
    "Sub3":"9"
    }               
              ]         
   }    
]

推荐答案

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添加到您的项目中,您可以在Package Manager控制台中使用此行来完成它.

Here is full example for your case. Also you need to add Newtonsoft.Json dll to your project you can do it with this line in the Package Manager Console.

Install-Package Newtonsoft.Json -Version 7.0.1

这篇关于如何从标题和详细信息类创建Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆