简体   繁体   中英

Grouping Json WebApi response by a value in c#

I want the Asp.net core Web API I am working on, to return Json response grouped by a value. The language is C#.

Suppose, this is the response it is generating now

{ 
    "Country" : "India",
    "City Name": "A",
    "Unit" : "A"

    "Country" : "India",
    "City Name": "B",
    "Unit" : "B"    

    "Country" : "UK",
    "City Name": "C",
    "Unit" : "C"    
}

But the response I want is something like this,

           "Country:India 
            [{
                "City Name": "A",
                "Unit" : "A"
             }

            {   
                "City Name": "B",
                "Unit" : "B"
            }]

I want the response to be grouped by country. Can someone help?

If I understand correctly, you are getting a response from an external API (correct if I'm wrong).

Then what you have to do is:

  1. Deserialize that response into a dynamic object, or an object of your choice,
  2. Parse it to the below C# example,
  3. Optionally you can serialize it again and pass further on.

JSON:

{
    "Country":{
        "CountryName": "India" ,
        "Cities":
        [
            {
                "CityName": "A",
                "Unit" : "A"
            },
            {   
                "CityName": "B",
                "Unit" : "B"
            }
        ]
    }
}

C#:

public class Response
{
    public Country Country { get; set; }
}

public class City
{
    public string CityName { get; set; }
    public string Unit { get; set; }
}

public class Country
{
    public string CountryName { get; set; }
    public List<City> Cities { get; set; }
}

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