Ali Eghbali
Ali Eghbali

Reputation: 11

convert list to json format in c#

In C#, I fill a list

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

with objects that hold job opportunities. I want convert "jobs" to JSON format like this:

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

How can i do that?

I tried but i got this result:

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

Upvotes: 0

Views: 633

Answers (2)

Luis M. Villa
Luis M. Villa

Reputation: 159

I think you should stick to the JSON serialization you got as result. This is what the consumer of a service, for example, expects to obtain. You have defined a list of items, and this should be serializated as an array of objects in JSON. If you want to obtains something like the code you wrote, you should define an object structure such as:

class CareerOportunities {
    public List<CareerOportunity> oportunities = new List<CareerOportunity>();
}

class CareerOportunity {
    public string JobTitle { get; set; }
    // more attributes here ...
}

This will be serialized as:

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

Upvotes: 1

Michel Amorosa
Michel Amorosa

Reputation: 495

It is normal to have "[]" because the list is converted to an array, you cannot have a list without "[]"

If you just want "{}" around, just return a single object

Upvotes: 0

Related Questions