My approximate data table structure which i will get from my sqlserver stored proc call. I am using .netframework 3.5 and i want to convert this datatable to json output using ado.net. i have stuck at GetCountryList(FK,TypeName) . Kindly help me to acheive the below json output. Thanks for your help in advance.
Type ID Name FK
Continent 1 America 0
Continent 2 Asia 0
Continent 3 Africa 0
Country 11 USA 1
Country 12 China 2
Country 13 India 2
Country 14 Kenya 3
DataEntity
public class UserData
{
public string Type { get; set; }
public string ID { get; set; }
public string Name { get; set; }
public string FK {get; set;}
}
Service Method
public static UserData GetUserData() {
JavaScriptSerializer jSerializer = new JavaScriptSerializer ();
DataTable dtUserData = DataAccess.getUserDataTable();
if(dtUserData !=null && dtUserData.Rows.Count>0)
{
List<DataRow> list = dtMasterData.AsEnumerable().ToList();
List<UserData> lstContinent = new List<UserData>();
List<UserData> lstCountry = new List<UserData>();
foreach(DataRow dr in list)
{
var objUserData = new UserData();
objUserData.ID = dr["ID"].ToString();
objUserData.Type = dr["Type"].ToString();
objUserData.Name = dr["Name"].ToString();
objUserData.FK = dr["FK"].ToString();
if(objUserData.Type.ToString().ToLower=="continent")
{
lstContinent.Add(objUserData);
}
if(objUserData.Type.ToString().ToLower=="country")
{
if(dr["FK"] !=null)
{
var ForgnKey = dr["FK"].ToString();
var TypeName = dr["Type"].ToString();
var CountriesList = GetCountryList(FK,TypeName) //how do i call a generic method to filter out the country list as per passing Continent FK?
lstCountry.AddRange(CountriesList);
}
lstCountry.Add(objUserData);
}
private static List<T> GetCountryList (lstCountry,ForgnKey,TypeName) //Not sure with the syntax
{
var CountriesList = lstCountry.Where(p=>p.FK==ForgnKey).ToList();
}
}
return jSerializer.Serialize(objUserData);
}
Expected JSON Output :
"data": {
"Contnient":
[
{ "Id": "1", "Type": "Contient", "Name" :"America","FK":"1" },
{ "Id": "2", "Type": "Contient", "Name" :"Asia", "FK":"2" },
{ "Id": "3", "Type": "Contient", "Name" :"Africa", "FK":"2" },
{ "Id": "4", "Type": "Contient", "Name" :"Asia", "FK":"2" }
],
"America":
{
"Country":
[
{ "Id": "11", "Type": "Country","Name":"India","FK":"1" }
]
},
"Asia:
{
"Country":
[ { "Id": "12", "Type": "Country","Name":"China","FK":"2" },
{ "Id": "13", "Type": "Country","Name":"India","FK":"2" }
]
}
"Africa":
{
"Country":
[ { "Id": "14", "Type": "Country","Name":"Kenya","FK":"3" }
]
}
Shouldn't the generic function be defined as:
private static List<T> GetCountryList<T>(lstCountry,ForgnKey,TypeName)
{
return lstCountry.Where(p=>p.FK==ForgnKey).ToList();
}
Then called as:
var CountriesList = GetCountryList<UserData>(lstCountry,FK,TypeName);
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.