Reputation: 61
I have created the class as below :
public class StudentRecord
{
[Key]
public Int ID { get; set; }
public String StudentName { get; set; }
}
For some reason, I need to do
list<StudentRecord> getStudentData = fnGetData(); // Get all data from SQL
string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(getStudentData);
But I just want jsondata
only get column StudentName
only.
That mean example of data is
[ "Peter", "Mary", "Sam", "Kim", "Hey" ]
Can I know how to do this ?
Thank you
Upvotes: 0
Views: 330
Reputation: 14218
You should select StudentName
into List
then SerializeObject
as you wish.
list<StudentRecord> getStudentData = fnGetData(); // Get all data from SQL
var studentNameList = getStudentData.Select(p => p.StudentName).ToList();
string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(studentNameList);
Updated
If you want to get one more columns, you can do it by return list of Anonymous Types like this
var studentNameList = getStudentData.Select(p => new { p.StudentName, p.ID }).ToList();
Upvotes: 0
Reputation: 4903
If you want to ignore the column, you can add the annotation [JsonIgnore]
:
public class StudentRecord
{
[Key]
public Int ID { get; set; }
public String StudentName { get; set; }
[JsonIgnore]
public String PropertyToIgnore{ get; set; }
}
Upvotes: 1
Reputation: 1685
We can use the Linq queries to select the required attribute from a collection of objects
string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(getStudentData.Select(s=>s.StudentName).ToList());
Upvotes: 0