我有角度应用程序,我试图以特定格式获取json。 我从数据库中提取数据,数据库有表数据
Country State
China chungchong
India hyderabad
USA florida
India delhi
USA redmond
我正在努力让json获得国家/地区列表以及每个国家/地区都有数组城市。
angular.module('app')
.factory('CountyStatesService', [
'$resource', function($resource) {
return $resource('/api/GetCountryStates/');
}
])
GetCountryStates()方法是一个csharp方法,只返回表中所有数据的列表。
我正在尝试按以下格式对json进行排序/分组
data: [
{ text: "China", items: [
{text: "chungchong"}
] },
{
text: "India", items: [
{ text: "Hyderabad" },
{ text: "Delhi" }
]
},
{
text: "USA", items: [
{ text: "Florida" },
{ text: "Redmond" }
]
}
]
但我正在让json完成分组。如何按预期实现json格式。
C#代码
[HttpGet]
public IEnumerable<CountrieStatesClass> GetCountryState()
{
return GetStructuredJson();
}
public IEnumerable<CountrieStatesClass> GetStructuredJson()
{
List<CountrieStatesClass> locations = new List<CountrieStatesClass>();
using (SqlConnection connection = new SqlConnection(MyConnectionString))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "select * from tblCountryStateDetails";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
CountrieStatesClass location = new CountrieStatesClass
{
CountryName = (string)reader["CountryName"],
StateName=(string)reader["StateName"]
};
locations.Add(location);
}
}
return locations;
}
}
答案 0 :(得分:4)
首先,我会将CountrieStatesClass
定义为更像这样
public class CountrieStatesClass
{
public string Text {get; set;}
public List<State> Items {get; set;}
}
public class State
{
public string Text {get; set;}
}
然后,像这样加载你的数据
CountrieStatesClass location = new CountrieStatesClass
{
Text = (string)reader["CountryName"],
Items = new List<State>{new State{ Text = (string)reader["StateName"] } }
};
locations.Add(location);
然后,你使用linq
return locations
.GroupBy(l => l.Text)
.Select(grp => new CountrieStatesClass
{
Text = grp.Key,
Items = grp.SelectMany(l => l.Items).ToList()
})
.ToList();
然后,您只需使用您已经使用的任何序列化工具序列化该对象。
注意有更好的方法来加载您的数据。我个人使用Entity Framework,但也有很多其他工具。
答案 1 :(得分:0)
您可以在一个 Linq 语句中完成所有操作。
public IHttpActionResult Get(Guid id)
{
...
var answers = objList.GroupBy(x => x.Category).Select(x => new { Category = x.Key, Items = x.ToArray() });
response.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(answers), System.Text.Encoding.UTF8, "application/json");
response.Headers.Add("total", objList.Count().ToString());
return ResponseMessage(response);
}