在c#中将列表转换为json格式

本文关键字:json 格式 转换 列表 | 更新日期: 2023-09-27 18:11:18

在c#中,我填充了一个列表

List<CareerOpportunities> jobs = new List<CareerOpportunities>();

对象包含工作机会。我想把"job"转换成JSON格式,像这样:

    {
    "Job Title":{
    "Sex":"...",
    "City":"...",
    "Date":"...",
    "ActivityField":"...",
    "Salary":"...",
    "WorkHours":"...",
    "Insurance":"..."
    "Address":"..."
    },
    .
    .
    .
    .
    }

我该怎么做呢?

我试过了,但我得到了这个结果:

[
{
"JobTitle":"...",
"Sex":"...",
"City":"...",
"Date":"...",
"ActivityField":"...",
"Salary":"... ",
"WorkHours":"...",
"Insurance":"...",
"Address":"...
},
.
.
.
.
]

在c#中将列表转换为json格式

我认为你应该坚持JSON序列化你得到的结果。例如,这是服务的消费者期望获得的。您已经定义了一个项目列表,并且应该将其序列化为JSON中的对象数组。如果您想获得与您编写的代码类似的东西,您应该定义一个对象结构,如:

class CareerOportunities {
    public List<CareerOportunity> oportunities = new List<CareerOportunity>();
}
class CareerOportunity {
    public string JobTitle { get; set; }
    // more attributes here ...
}

这将被序列化为:

{
    "oportunities": [
        {
            "JobTitle": "..."
        },
        {
            "JobTitle": "..."
        }
        ...
    ]
}

有"[]"是正常的,因为列表被转换为数组,所以不能没有"[]"

如果你只想要"{}",只返回一个对象