简体   繁体   中英

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

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.

The main issue if that your service is returning an array, if that is not intended you should change that method so it returns an object.

If you know what you are returning, you could try to use Newtonsoft.Json to deserialize from a C# object.

Creating the C# class

Let's say that we have this class:

using Newtonsoft.Json;

// Naming the class Person, I assume it is a person.
public class Person
{
    [JsonProperty("name")]
    public string Name { get; set; }
    [JsonProperty("primaryLastName")]
    public string PrimaryLastName { get; set; }
    [JsonProperty("secondaryLastName")]
    public string SecondaryLastName { get; set; }
    [JsonProperty("degrees")]
    public string Degrees { get; set; }
    [JsonProperty("roles")]
    public string Roles { get; set; }
    [JsonProperty("entityId")]
    public string EntityId { get; set; }
    [JsonProperty("enrollment")]
    public string Enrollment { get; set; }
    [JsonProperty("photo")]
    public string Photo { get; set; } // Is it a string?
    [JsonProperty("groupsInfo")]
    public GroupsInfo GroupInfo { get; set; }
    [JsonProperty("birthDate")]
    public string BirthDate { get; set; }
    public class GroupsInfo
    {
        [JsonProperty("required")]
        public string Required { get; set; }
        [JsonProperty("optional")]
        public string Optional { get; set; }
    }
}

This class contains all the properties of the JSON file. The JsonProperty("PropertyName") attribute name allows the parser/serializer to recognize the keys when parsing and serializing the JSON file.

Declaring the class and serializing to JSON

From your service, you can use this class to create the JSON object like this:

Person person = new Person() {
  Name = Dname,
  PrimaryLastName = DprimaryLastName,
  SecondaryLastName = DsecondLastName,
  Degrees = Ddegrees,
  Roles = Droles,
  EntityId = DentityId,
  Enrollment = Denrollment,
  Photo = Dphoto,
  GroupsInfo = new Person.GroupsInfo("optional", "required"), // Don't forget to add the constructor.
  BirthDate = DbirthDate
};

And then, using the below line, you can serialize it to a string:

using Newtonsoft.Json;

...

string GetSerializedDataFromPerson(Person person)
{
    return JsonConvert.SerializeObject(person, Formatting.Indented);
}

This can be sent from the service to the app, since it is now formatted as a JSON, or you can create a file that contains the formatted json content.

Parsing the JSON file to the C# class

To get your data, you would firstly fetch your JSON file content as string , from any source.

After that, you could use the following code:

using Newtonsoft.Json;

...

string json = /* Read file, get from server */;
Person person = JsonConvert.DeserializeObject<Person>(json);

System.Diagnostics.Debug.WriteLine($"First name {person.Name}");
// The above code will show the parsed person json name.

You can then mess with it to make it working as your expectations. Although, it seems like some parts of your JSON have to be reviewed, the design might not be the best.

Some keys like required or optional look like to be a bool , and is is not possible to return a string[] if the service returns a string .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM