C# Web API Merge Elements Into Single Element (with Objects) - c#

I am building a C# Web API and its purpose is to enable an external company to retrieve student data (they call them 'roles') via a GET call to the API I am building. Now, they have the choice of either retrieving all students via a call to https://localhost:XXXXX/custom-roles-api/campusCustomRoles or to retrieve a single student it'd be https://localhost:XXXXX/custom-roles-api/campusCustomRoles/123456 with '123456' being the student Id number. Some students have one row of data as they below to a single department, so the JSON return in the GET call shows them in a single element, however for students who belong to 2 or more departments, the return shows more than one element, for example;
{
"roles": [
[
"STUDENT",
"UG",
2,
"Politics",
"Smith, John",
123456
],
[
"STUDENT",
"UG",
2,
"Religions",
"Smith, John",
123456
]
]
}
In the above example, student John Smith belongs to 2 departments (Religions and Politics) and this is represented in two elements in the JSON return. What the external company have requested is for a single element which would look like this and this is where I am stuck;
{
"roles": [
[
"STUDENT",
"UG",
2,
"Politics",
"Religions",
"Smith, John",
123456
]
]
}
I hasten to add that it was also one of the requirements to return only the Object values without the keys (or column names).
The Below is what my Roles Class looks like;
public class Roles
{
List<Roles> studentRoles = new List<Roles>();
public int UserName { get; set; }
public string PersonName { get; set; }
public string Profile { get; set; }
public string Level { get; set; }
public int Year { get; set; }
public string Department { get; set; }
}
public class readRoles : Roles
{
public readRoles(DataRow dataRow)
{
UserName = (int)dataRow["UserName"];
PersonName = (string)dataRow["PersonName"];
Profile = (string)dataRow["Profile"];
Level = (string)dataRow["Level"];
Year = Convert.ToInt32(dataRow["Year"]);
Department = (dataRow["Department"] == DBNull.Value) ? "No Department" : dataRow["Department"].ToString();
}
public int UserName { get; set; }
public string PersonName { get; set; }
public string Profile { get; set; }
public string Level { get; set; }
public int Year { get; set; }
public string Department { get; set; }
}
And below, I have this in my Controller;
public HttpResponseMessage Get(int id)
{
string connString;
SqlConnection con;
connString = #"XXXXXXXXXX";
DataSet _ds = new DataSet();
con = new SqlConnection(connString);
con.Open();
var sql = #"select distinct CONCAT(CONCAT(mytable.surname, ', '),dbo.initcap(mytable.forenames)) as 'PersonName'
,convert(int,mytable.studentID) as 'UserName'
,mytable.category as 'Profile'
,mytable.level as 'Level'
,mytable.year as 'Year'
,mytable.depat as 'Department'
from MYTABLE
WHERE convert(int,mytable.studentID) = #UserName
order by 2 desc ";
SqlParameter param = new SqlParameter();
param.ParameterName = "#UserName";
param.Value = id;
SqlCommand CMD2 = new SqlCommand(sql, con);
CMD2.Parameters.Add("#UserName", SqlDbType.Int).Value = id;
CMD2.Connection = con;
CMD2.CommandText = sql;
CMD2.CommandType = System.Data.CommandType.Text;
SqlDataReader dr = CMD2.ExecuteReader();
SqlDataAdapter _adapter = new SqlDataAdapter(sql, con);
_adapter = new SqlDataAdapter
{
SelectCommand = new SqlCommand(sql, con)
};
_adapter.SelectCommand.Parameters.AddWithValue("#UserName", id);
_adapter.Fill(_ds, "roles");
List<Roles> roles = new List<Roles>(_ds.Tables[0].Rows.Count);
if (_ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow studentrole in _ds.Tables[0].Rows)
{
roles.Add(new readRoles(studentrole));
}
}
foreach (DataRow drow in _ds.Tables[0].Rows)
{
var item = new List<object>();
item.Add((string)drow["Profile"]);
item.Add((string)drow["Level"]);
item.Add(Convert.ToInt32(drow["Year"]));
item.Add((drow["Department"] == DBNull.Value) ? "No Department" : drow["Department"].ToString());
item.Add((string)drow["PersonName"]);
item.Add((int)drow["UserName"]);
studentRoles.Add(item);
};
var response = Request.CreateResponse(HttpStatusCode.OK, new { roles = studentRoles });
// The below part of the code is where the departments are merged but this solution only works if there are only 2 departments, but there are many cases where a student has more than 2 departments
if (roles.Count() > 1)
{
for (int i = 0; i < studentRoles[0].Count(); i++)
{
if (studentRoles[0][i].ToString() != studentRoles[1][i].ToString())
{
var arr = new JArray();
arr.Add(studentRoles[0][i]);
arr.Add(studentRoles[1][i]);
studentRoles[0][i] = arr;
}
}
studentRoles[1].Clear()
}
return response;
}
The problem I am having is that, my code works as expected but ONLY if a student belongs to only 2 departments, like our example above, John Smith. I need help tweaking the above last bit of code to accommodate students who will be returned with more than 2 elements as some belong to multiple departments. For example, if John Smith belonged to 3 departments;
{
"roles": [
[
"STUDENT",
"UG",
2,
"Politics",
"Smith, John",
123456
],
[
"STUDENT",
"UG",
2,
"Religions",
"Smith, John",
123456
],
[
"STUDENT",
"UG",
2,
"Languages",
"Smith, John",
123456
]
]
}
I would expect John Smith's return to look like this;
{
"roles": [
[
"STUDENT",
"UG",
2,
"Politics",
"Religions",
"Languages",
"Smith, John",
123456
]
]
}
Eventually, the external company's requirement would be for students' Modules to be included, and of course students will have multiple Modules, but I'll cross that bridge when I get there, ha! Any help would be appreciated.

add to your code my solution https://stackoverflow.com/a/75485207/11392290
var roles = JArray.From(studentRoles);
if (roles.Count() > 1)
{
.... use my code
}
var response = Request.CreateResponse(HttpStatusCode.OK, new { roles = roles });

Related

create a sublist in list, for only one column

I have two sql records with different Address, I'm trying to make it as one record by using sublist
public class spproperty
{
public string Name{ get; set; }
public string Addr{ get; set; }
public int ID{ get; set; }
}
List<spproperty> lst = new List<spproperty>();
lst = db.sp_getDetails(inputParameter).ToList();//gets result from stored procedure as in example
Example:
Name Addr ID
John Florida 234
John Arizona 234
Expected Output in json from list
[
{
"Name": "John",
"Addresses" : {
"Addr" : "Florida",
"Addr" : "Arizona"
},
"ID": 234,
}
]
I tried in xelement with dataset it worked, Any suggestions with list
You can group by Name and ID then make the desired formatted list using linq. I think the following code will work for your scenario:
var desiredList = lst.GroupBy(x => new { Name = x.Name, ID = x.ID })
.Select(x => new
{
Name = x.FirstOrDefault().Name,
Addresses = x.Select(y => y.Addr).ToList(),
ID = x.FirstOrDefault().ID
}).ToList();
After that you can convert the result to Json if you want.

How to create hierarchy in json string from string array?

I am trying to generate json string for the hierarchy like below:
Company(select * from Company)
Department(select * from Department)
Employee(select * from Employee)
Each of the above query will return fields like below:
Company Fields - (Id,Name,Location)
Department Fields - (Id,Name,CompanyId)
Employee Fields - (Id,Name,DepartmentId)
Now I am trying to generate JSON string for above entities like below:
Expected output:
{
"Id": "",
"Name": "",
"Location": "",
"Department":
{
"Id": "",
"Name": "",
"CompanyId": "",
"Employee" :
{
"Id": "",
"Name": "",
"DepartmentId": "",
}
}
}
Code:
public string GetData(Child model,List<Parent> parents)
{
var fields = new List<string[]>();
if (parents != null)
{
foreach (var parent in parents)
{
var columns = GetColumns(parent); //returns string[] of columns
fields.Add(columns);
}
}
fields.Add(GetColumns(model));
string json = JsonConvert.SerializeObject(fields.ToDictionary(key => key, v => string.Empty),
Formatting.Indented);
return json;
}
Now when I don't have any parents and want to generate json string for only child then below code is working fine:
string json = JsonConvert.SerializeObject(fields.ToDictionary(key => key, v => string.Empty),Formatting.Indented)
Output :
{
"Id": "",
"Name": "",
"Location": "",
}
But now I want to generate JSON for my hierarchy with any such inbuilt way.
I know I can loop,append and create json string but I want to do this in better way like I have done for my child.
Update:
public class Child
{
public string Name { get; set; } // Contains Employee
//Other properties and info related to process sql query and connection string
}
public class Parent
{
public string Name { get; set; } // Contains Company,Department.
public string SqlQuery { get; set; } // query related to Company and Department.
//Other properties and info related to connection string
}
I created a class that holds the Information similarly to what you proposed, in a child-parent structure. I also added a custom little Parser that works recursively. Maybe that's what you need and/or what gives you the ideas you need to fix your problem.
I also altered the output a little bit, by adding the angled brackets ( "[ ]" ). I think that's what you will need with multiple children. At least that's what the JSON validator tells me that I posted below. If you don't need/ want them, just remove them in the parser.
I don't think you can use the parser you used in your example without having some form of extra fields like I showed in my previous answer, since those parsers usually go for property names as fields and I guess you don't want to create classes dynamically during runtime.
I also don't think that it is possible for you to create a dynamic depth of your parent-child-child-child...-relationship with Lists, Arrays or Dictionaries, because those structures have a set depth as soon as they are declared.
Class:
public class MyJsonObject
{
public List<string> Columns = new List<string>();
public string ChildName;
public List<MyJsonObject> Children = new List<MyJsonObject>();
}
Parser:
class JsonParser
{
public static string Parse(MyJsonObject jsonObject)
{
string parse = "{";
parse += string.Join(",", jsonObject.Columns.Select(column => $"\"{column}\": \"\""));
if (!string.IsNullOrEmpty(jsonObject.ChildName))
{
parse += $",\"{jsonObject.ChildName}\":";
parse += $"[{string.Join(",", jsonObject.Children.Select(Parse))}]";
}
parse += "}";
return parse;
}
}
Usage:
class Program
{
static void Main(string[] args)
{
MyJsonObject company = new MyJsonObject();
company.ChildName = "Department";
company.Columns.Add("Id");
company.Columns.Add("Name");
company.Columns.Add("Location");
MyJsonObject department = new MyJsonObject();
department.ChildName = "Employee";
department.Columns.Add("Id");
department.Columns.Add("Name");
department.Columns.Add("CompanyId");
MyJsonObject employee1 = new MyJsonObject();
employee1.Columns.Add("Id");
employee1.Columns.Add("Name");
employee1.Columns.Add("DepartmentId");
MyJsonObject employee2 = new MyJsonObject();
employee2.Columns.Add("Id");
employee2.Columns.Add("Name");
employee2.Columns.Add("DepartmentId");
company.Children.Add(department);
department.Children.Add(employee1);
department.Children.Add(employee2);
var json = JsonParser.Parse(company);
}
}
Output and Link to JSON-Validator:
https://jsonformatter.curiousconcept.com/
{
"Id":"",
"Name":"",
"Location":"",
"Department":[
{
"Id":"",
"Name":"",
"CompanyId":"",
"Employee":[
{
"Id":"",
"Name":"",
"DepartmentId":""
},
{
"Id":"",
"Name":"",
"DepartmentId":""
}
]
}
]
}
Perhaps I'm missing something. If you create the classes you need in the heirachy, instantiate them with data and then serialize them, the structure will be created for you.
using System.Web.Script.Serialization;
public class Employee
{
public int Id {get; set; }
public string Name {get; set; }
public int DepartmentId {get; set; }
}
public class Department
{
public int Id {get; set; }
public string Name {get; set; }
public string CompanyId {get; set; }
public List<Employee> {get; set;}
}
public class Company {
public int Id {get; set; }
public string Name {get; set; }
public string Location {get; set; }
public List<Department> {get; set;}
}
var myCompany = new Company();
// add departments and employees
var json = new JavaScriptSerializer().Serialize(myCompany);
You can use dynamic:
//here your database
dynamic[] company = new object[] { new { Name = "Company1", DepartmentId = 1 }, new { Name = "Company2", DepartmentId = 2 } };
dynamic[] department = new object[] { new { DepartmentId = 1, Name = "Department1" }, new { DepartmentId = 2, Name = "Department2" } };
//select from database
var data = from c in company
join d in department on c.DepartmentId equals d.DepartmentId
select new {Name = c.Name, Department = d};
var serialized = JsonConvert.SerializeObject(data);
result:
[
{
"Name": "Company1",
"Department": {
"DepartmentId": 1,
"Name": "Department1"
}
},
{
"Name": "Company2",
"Department": {
"DepartmentId": 2,
"Name": "Department2"
}
}
]
Ok, lets try like this. First of all as i understand your preblem: u have arrays of properties of parents and child and u neet to convert it to json object.
The point is here:
public static ExpandoObject DicTobj(Dictionary<string, object> properties)
{
var eo = new ExpandoObject();
var eoColl = (ICollection<KeyValuePair<string, object>>)eo;
foreach (var childColumn in properties)
eoColl.Add(childColumn);
return eo;
}
U use dynamic and ExpandoObject to convert dictionary to object
The other code is trivial: u put all your objects to one using dynamic type
and serialize it.
The full code:
public static Child Child1 { get; set; } = new Child
{
Name = "Child1"
};
public static Parent Parent1 { get; set; } = new Parent
{
Name = "Parent1"
};
public static Parent Parent2 { get; set; } = new Parent
{
Name = "Parent2"
};
private static void Main(string[] args)
{
var result = GetData(Child1, new List<Parent> {Parent1, Parent2});
Console.WriteLine(result);
}
/// <summary>
/// This is the magic: convert dictionary of properties to object with preperties
/// </summary>
public static ExpandoObject DicTobj(Dictionary<string, object> properties)
{
var eo = new ExpandoObject();
var eoColl = (ICollection<KeyValuePair<string, object>>) eo;
foreach (var childColumn in properties)
eoColl.Add(childColumn);
return eo;
}
public static string GetData(Child model, List<Parent> parents)
{
var childColumns = GetColumns(model);
dynamic child = DicTobj(childColumns);
var parentsList = new List<object>();
foreach (var parent in parents)
{
var parentColumns = GetColumns(parent);
var parentObj = DicTobj(parentColumns);
parentsList.Add(parentObj);
}
child.Parents = parentsList;
return JsonConvert.SerializeObject(child);
}
/// <summary>
/// this is STUB method for example
/// I change return type from string[] to Dictionary[columnName,ColumnValue], becouse u need not only column names, but
/// with it values, i gues. If not, look commented example at the end of this method
/// </summary>
public static Dictionary<string, object> GetColumns(object model)
{
var result = new Dictionary<string, object>();
if (model == Child1)
{
result.Add("Id", "1");
result.Add("Name", "Child1");
result.Add("Location", "SomeLocation");
}
if (model == Parent1)
{
result.Add("Id", "2");
result.Add("Name", "Parent1");
result.Add("SomeProperty1", "SomeValue1");
}
if (model == Parent2)
{
result.Add("Id", "3");
result.Add("Name", "Parent1");
result.Add("SomeProperty3", "SomeValue2");
}
//if u have only columNames and dont need values u can do like this
//var columns = new[] {"Id", "Name", "SomeProperty1"};//this u get from DB
//return columns.ToDictionary(c => c, c => new object());
return result;
}
}
public class Child
{
public string Name { get; set; } // Contains Employee
//Other properties and info related to process sql query and connection string
}
public class Parent
{
public string Name { get; set; } // Contains Company,Department.
public string SqlQuery { get; set; } // query related to Company and Department.
//Other properties and info related to connection string
}
And result output:
{
"Id": "1",
"Name": "Child1",
"Location": "SomeLocation",
"Parents": [
{
"Id": "2",
"Name": "Parent1",
"SomeProperty1": "SomeValue1"
},
{
"Id": "3",
"Name": "Parent1",
"SomeProperty3": "SomeValue2"
}
]
}
You can pass any kind of object even if you don't have a fixed structure:
Newtonsoft.Json.JsonConvert.SerializeObject(new yourCustomObject)
By using this.
The best way to to get this result
- You have to create a new class which has the relation of all the class. Then use the
Newtonsoft.Json.JsonConvert.SerializeObject(new organization )
Let creates a new class named organization . Add the relation which you want to see in Json. Then convert into the JSON using JsonConvert.
Or you can use the following dynamic loop
//here your database<br/>
dynamic[] company = new object[] { new { Name = "Company1", DepartmentId = 1 }, new { Name = "Company2", DepartmentId = 2 } };
dynamic[] department = new object[] { new { DepartmentId = 1, Name = "Department1" }, new { DepartmentId = 2, Name = "Department2" } };
//select from database<br/>
var data = from c in company
join d in department on c.DepartmentId equals d.DepartmentId
select new {Name = c.Name, Department = d};
var serialized = JsonConvert.SerializeObject(data);

Querying nested objects using linq query with join

I have the following json structure that I am getting from an api:
{
"event_instance": [
{
"id": 55551244,
"event_id": 11112,
"name": "Brown Belt Karate Class",
"staff_members": [
{
"id": 12345,
"name": "John Smith"
}
],
"people": [
{
"id": 111,
"name": "Jane Doe"
},
{
"id": 222,
"name": "Josh Smith"
},
{
"id": 333,
"name": "Ben Johnson"
}
],
"visits": [
{
"id": 1234578,
"person_id": 111,
"state": "completed",
"status": "complete"
},
{
"id": 1239865,
"person_id": 222,
"state": "completed",
"status": "complete"
},
{
"id": 1239865,
"person_id": 333,
"state": "canceled",
"status": "cancel"
}
]
}
]
}
I am deserializing this into the following .net objects using JSON.NET:
[JsonObjectAttribute("event_instance")]
public class EventInstance
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("event_id")]
public int EventId { get; set; }
[JsonPropertyAttribute("name")]
public string Name { get; set; }
[JsonPropertyAttribute("staff_members")]
public List<StaffMember> StaffMembers { get; set; }
[JsonPropertyAttribute("visits")]
public List<Visit> Visits { get; set; }
[JsonPropertyAttribute("people")]
public List<Student> Students { get; set; }
}
[JsonObjectAttribute("staff_members")]
public class StaffMember
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("name")]
public string Name { get; set; }
}
[JsonObjectAttribute("people")]
public class People
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("name")]
public string Name { get; set; }
}
[JsonObjectAttribute("visits")]
public class Visits
{
[JsonPropertyAttribute("id")]
public int Id { get; set; }
[JsonPropertyAttribute("person_id")]
public int PersonId { get; set; }
[JsonPropertyAttribute("state")]
public string State { get; set; }
[JsonPropertyAttribute("status")]
public string Status { get; set; }
}
I am using the following code to de-serialize:
var event = (EventInstance)JsonConvert.DeserializeObject(json, typeof(EventInstance));
The above works fine and gives me an accurate object representation of the above json structure. Now I am trying to query this event object to filter/project to a new structure that I can then serialize back to json and send down to the browser. I need to return a list of students for the event that are in a state of "completed" and a status of "complete". As you can see, the people array ties to the visits array (with id and person_id). I would like to produce the following simple output:
11112, Brown Belt Karate Class, John Smith, 111, Jane Doe
11112, Brown Belt Karate Class, John Smith, 222, Josh Smith
I have tried something like this:
var studentList = from theClass in event
from staff in theClass.StaffMembers
from student in theClass.People
from visits in theClass.Visits
where visits.Status == "complete"
&& visits.State == "completed"
select new
{
event_id = theClass.EventId
class_name = theClass.Name,
instructor_name = staff.Name,
student_id = student.Id,
student_name = student.Name
};
string _data = JsonConvert.SerializeObject(studentList);
Naturally this produces duplicate student names. I am new to linq. Basically I need to join/tie the people and visits array so I just get back a single student for that id, along with the root data for this event. Any advice on a better way to do this is much appreciated too!
The trick is to join the students and visits into a collection that contains data of both:
from ei in eventInstances
from sm in ei.StaffMembers
from x in
(from vi in ei.Visits
join st in ei.Students on vi.PersonId equals st.Id
select new { vi, st }) // Here you get students and visits side-by-side
select new
{
ei.EventId,
Event = ei.Name,
StaffMemeber = sm.Name,
PersonId = x.st.Id,
Student = x.st.Name
}

Formatting JSON response

====Summary====
I need some help trying to format my JSON response. I'm using ASP.Net with a Model and a Controller.
====Information====
I am working on a web api in ASP.Net. I have a SQL backend in which I fetch some data and put it into a DataTable. My DataTable looks like this:
+----+-------+-------+
| ID | Title | Users |
+----+-------+-------+
| 1 | Test | user1 |
| 1 | Test | user2 |
+----+-------+-------+
NOTE: One record can have multiple users which is why ID is "1" for both rows ("ID" is not the unique ID of the actual SQL table row but rather a foreign key...anyway, I digress... )
I have created a Model in C# that looks like this:
public class Record
{
public int ID { get; set; }
public string Title {get; set;}
public string Users {get; set;}
}
Finally my Controller looks like this
DataBaseHelper db = new DataBaseHelper();
public IEnumerable Get_Record(string id)
{
// Get DataTable
DataTable dt = new DataTable();
dt = db.GetRecord(id);
foreach (DataRow row in dt.Rows)
{
yield return new Record
{
ID = row.Field("ID"),
Title = row.Field("Title"),
Users = row.Field("Users")
};
}
}
When I call the API I get this:
[
-{
ID: 1,
Title: "Test",
Users: "user1"
},
-{
ID: 1,
Title: "Test",
Users: "user2"
}
]
====QUESTION====
How would I get the JSON response to look something sort of like this (if possible):
{
"Response":
[
{
ID: 1,
Title: "Test",
Users:
[
{name: "user1"},
{name: "user2"}
]
}
]
}
If that is not possible then this would be great as well:
"Response":
[
{
ID: 1,
Title: "Test",
Users: "user1"
},
{
ID: 1,
Title: "Test",
Users: "user2"
}
]
To expand upon #Shahrooz Jefri's answer, you can return an HttpResponseMessage which will allow you to return an anonymous object, but to get the result formatted as required, you will need to modify the Get_Record method:
public HttpResponseMessage Get_Record(string id)
{
// Get DataTable
DataTable dt = new DataTable();
dt = db.GetRecord(id);
var records = dt.Rows.Select(r => new Record()
{
ID = row.Field("ID"),
Title = row.Field("Title"),
Users = row.Field("Users")
});
return this.Request.CreateResponse(HttpStatusCode.OK,
new
{
Response = new
{
ID = records.First().ID,
Title = records.First().Title,
Users = records.Select(r => r.Users)
}
});
}
With this approach, we first transform the results from a call to db.GetRecord into an IEnumerable<Record> of your your Record object.
From there, we can shape an anonymous object to match your formatting requirements. Note that in my answer I have not applied any error checking; you should, as the case where db.GetRecord returns no results will cause an exception when we populate the ID and Title fields of the response object due to calls to records.First().
You can return your own format with anonymous Object.
Please See this:
public HttpResponseMessage Get()
{
return this.Request.CreateResponse(
HttpStatusCode.OK,
new { Message = "Hello", Value = 123 });
}
Well, What I have experienced so far, creating a generic response will be the best practice for your case. For instance, you may have a class something like this.
public enum Status
{
OK = 1,
ERROR = -1,
}
public class ResponseDTO
{
public static ResponseDTO CreateDynamicResponse(object content)
{
return new ResponseDTO {Status = Status.OK, Content = content};
}
public static ResponseDTO CreateDynamicResponseFromException(RovlerBaseException ex)
{
return new ResponseDTO
{
Status = Status.ERROR,
Message = ex.Message,
};
}
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Status Status;
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public object Content { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; set; }
}
After the execution of action I create an ActionFilterAttribute in order to check if there is an error on response that action just returned. Then I user CreateDynamicResponse or CreateDynamicResponseFromException with respect to the status of returned object.

Create JSON multi-level with Json.NET in c#

i have 2 class:
class Employee
{
string name;
string age;
}
class Departments
{
string branch;
Employee A;
}
Declare new list:
List<Departments> lstDp = new List<Departments>();
after get/set and Add Employee into the list ... i have a LIST of Departments include Employee info. And then:
string json = JsonConvert.SerializeObject(lstDp, Newtonsoft.Json.Formatting.Indented);
but the output JSON string only contain element "branch". What's wrong with this? I want the output like this:
[
{
"branch": "NY",
"Employee": {
"name": "John Smith",
"age": "29",
}
}
]
The problem can be that some of class members is private. Just tested:
class Employee
{
public string Name { get; set; }
public string Age { get; set; }
}
class Departments
{
public string Branch { get; set; }
public Employee Employee { get; set; }
}
And
var lstDp = new List<Departments> {
new Departments {
Branch = "NY",
Employee = new Employee { Age = "29", Name = "John Smith" }
}
};
var json = JsonConvert.SerializeObject(lstDp, Formatting.Indented);
Works fine.
The Departmentshould contain an IEnumerable<Employee> not just an Employee

Categories