C#Json从Class格式化

时间:2016-01-28 14:34:34

标签: c# json

我有一个C#类

public class occ
{
    public datetime from    { get; set; }
    public datetime to      { get; set; }
    public string   Ktype   { get; set; }
    public flag     bool    { get; set; }
}

我从来自存储过程的EF6.0函数中填写

我被要求为该类的每个记录创建一个这种格式的Json

{
"Ktype": [
    {
        "from"
        "to"
        "flag"
    }
]

}

我对Json有一点经验。这里的一些人帮助我赶上了。

到现在为止,我知道“外部”属性(我不知道如何称呼它......对不起)来自班级名称。

在此示例中, Ktype 是该类的一部分。

我如何Json序列化这个类并将Ktype作为外部Json attrib?

我想要这样的事情:

 {
        "TRC": [{"from":"2016-02-09","to":"2016-02-16","flag":true}]
 }

{
        "TRX": [{"from":"2016-02-12","to":"2016-02-18","flag":false}]
}

4 个答案:

答案 0 :(得分:3)

如果我理解正确,也许这会对你有所帮助:

public class occ
{
    public List<Ktype> ktype { get; set;}

    public occ()
    {
        this.ktype = new List<Ktype>();
    }
}

public class Ktype
{
    public datetime from    { get; set; }
    public datetime to      { get; set; }
    public flag     bool    { get; set; }
}

答案 1 :(得分:1)

填充和序列化时的以下内容会产生下面的json

public class Root
{
    public List<Ktype> Ktype { get; set; } = new List<Ktype>();
}
public class Ktype
{
    public DateTime from { get; set; }
    public DateTime to { get; set; }
    public bool flag { get; set; }
}

JSON:

{
    "Ktype": [{
        "from": "2016-01-28T14:43:10.3103658+00:00",
        "to": "2016-01-28T14:43:10.3103658+00:00",
        "flag": true
    }]
}

答案 2 :(得分:1)

使用来自newtonsoft lib的SerializeObject

string json = JsonConvert.SerializeObject(new occ(), Formatting.Indented);

了解更多信息check this

答案 3 :(得分:0)

像这样创建一个KTypeDto

public class KTypeDto
{
    public List<KType> KTypes { get; set;}
}

public class KType
{
    public Datetime From { get; set; }
    public Datetime To { get; set; }
    public Flag Bool { get; set; }
}