Tuesday, July 26, 2022

[FIXED] How can I return a C# Object instead of array JSON

Issue

I have this code

return Ok(

new object[]  
{
new { name = Dname, primaryLastName =DprimaryLastName, secondLastName= DsecondLastName,degrees= Ddegrees, roles= Droles, entityId = DentityId, enrollment = Denrollment, payrollNumber = DpayrollNumber, photo = Dphoto,  groupsInfo = rt , birthDate = DbirthDate} 
}

);

All variables values are string, except rt:

var rt = new Dictionary<string, string>();

foreach (DataTable table in dsgroupsinfo.Tables)
{
foreach (DataRow dr in table.Rows)
{
rt.Add("required", dr["requerido"].ToString());
rt.Add("optional", dr["opcional"].ToString());
}
}

My result from the service is this:

[
    {
        "name": "string",
        "primaryLastName": "string",
        "secondLastName": "string",
        "degrees": "string",
        "roles": "string",
        "entityId": "string",
        "enrollment": "string",
        "payrollNumber": "string",
        "photo": "string",
        "groupsInfo": {
            "required": "string",
            "optional": "string"
        },
        "birthDate": "string"
    }
]

how can I get a response like this:

{
    "name": "string",
    "primaryLastName": "string",
    "secondaryLastName": "string",
    "degrees": "string",
    "roles": "string",
    "entityId": "string",
    "enrollment": "string",
    "photo": "",
    "groupsInfo": {
        "required":["string"],
        "optional": ["string"]
    }
}

Please note there is no square brackets in the begining and the end, and inside groups info there are square brackets.

Hope you can help me, thanks.


Solution

Looks like you need to remove the outer array, and use a list for the dictionary value

var required = new List<string>>();
var optional = new List<string>>();
foreach (DataTable table in dsgroupsinfo.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        required.Add(dr["requerido"].ToString());
        optional.Add(dr["opcional"].ToString());
    }
}
var rt = new Dictionary<string, List<string>>
{
    {"required", required},
    {"optional", optional},
};

return Ok(
    new {
        name = Dname,
        primaryLastName = DprimaryLastName,
        secondLastName = DsecondLastName,
        degrees = Ddegrees,
        roles = Droles,
        entityId = DentityId,
        enrollment = Denrollment,
        payrollNumber = DpayrollNumber,
        photo = Dphoto,
        groupsInfo = rt,
        birthDate = DbirthDate
    } 
);

Ideally you would use a proper object model, as the other answer has shown.



Answered By - Charlieface
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.