Here is my class:
public class Root
{
public string ROOM_ID { get; set; }
public string ASSOCIATE { get; set; }
public string TVMAC { get; set; }
public bool STATUS { get; set; }
}
Here is JSON:
[{
"ROOM_ID": "Office 202",
"ASSOCIATE": "Franklin",
"TVMAC": "00-20-7F-00-03-3C",
"STATUS": true,
},
{
"ROOM_ID": "Office 210",
"ASSOCIATE": "Boomer",
"TVMAC": "00-20-7F-10-03-3B",
"STATUS": false,
}]
Here is snippet in C#
string json = [ {"ROOM_ID": "OFFICE 210", "ASSOCIATE":
"Boomer","TVMAC": "00-20-7F-10-03-3B ","STATUS": false},{"ROOM_ID":
"OFFICE 202", "ASSOCIATE": "Franklin","TVMAC": "00-20-7F-00-03-3C
","STATUS": true}]
Next is how to deserialize the above string to populate to Public Class Root
I've tried:
List root = JsonConvert.DeserializeObject<List>(json);
But get an error:
"Cannot deserialize JSON array into type 'OfficeWebServer.RootObject'. Line 1,
position 1"
Any thoughts and help is appreciated.
Related
I have the following get method which returns out of stock items in my database. My database is broken up into 2 tables, one called stock and one called Issue. My stock table is joined on the issue table (Both of them have IssueId in them)
When i run the following code:
public IEnumerable<Stock> GetOutOfStock(int page)
{
var stock = (from s in _context.Set<Stock>().Cast<Stock>()
where s.AvailableQty == 0
orderby s.Issue.PublicationDate descending
select s).Skip(25 * page).Take(25);
//.Include(s => s.Issue)
return stock;
}
I get this as my output:
{
"stockReferenceId": 32681,
"issueId": 7980,
"condition": "Fine",
"availableQty": 0,
"price": 51.94,
"comments": null,
"issue": null,
"supplierOrders": [],
"supplierQuotes": []
}
but as soon as i Include my Issue table with the following code:
public IEnumerable<Stock> GetOutOfStock(int page)
{
var stock = (from s in _context.Set<Stock>().Cast<Stock>()
where s.AvailableQty == 0
orderby s.Issue.PublicationDate descending
select s).Include(s => s.Issue).Skip(25 * page).Take(25);
//
return stock;
}
I get the following output
{
"StockReferenceId": 0,
"IssueId": 0,
"Condition": "string",
"AvailableQty": 0,
"Price": 0,
"Comments": "string",
"Issue": {
"IssueId": 0,
"Title": "string",
"PublicationDate": "2020-02-17T08:55:27.501Z",
"Publisher": "string",
"SeriesNumber": 0,
"Description": "string",
"CoverImage": "string",
"ComicCreators": [
{
"IssueId": 0,
"CreatorId": 0,
"CreatorRole": "string",
"Creator": {
"CreatorId": 0,
"Name": "string",
"CountryOfResidence": "string",
"TaxReferenceNumber": "string",
"EmailAddress": "string",
"ComicCreators": [
null
]
}
}
My domain tables look like this:
Stock:
public Stock()
{
//Cart = new HashSet<Cart>();
//OrderDetails = new HashSet<OrderDetails>();
SupplierOrders = new HashSet<SupplierOrders>();
SupplierQuotes = new HashSet<SupplierQuotes>();
}
public int StockReferenceId { get; set; }
public int? IssueId { get; set; }
public string Condition { get; set; }
public short? AvailableQty { get; set; }
public decimal? Price { get; set; }
public string Comments { get; set; }
public Issues Issue { get; set; }
and my Issue table looks like this:
public partial class Issues
{
public Issues()
{
ComicCreators = new HashSet<ComicCreators>();
Stock = new HashSet<Stock>();
}
public int IssueId { get; set; }
public string Title { get; set; }
public DateTime? PublicationDate { get; set; }
public string Publisher { get; set; }
public short? SeriesNumber { get; set; }
public string Description { get; set; }
public string CoverImage { get; set; }
public ICollection<ComicCreators> ComicCreators { get; set; }
public ICollection<Stock> Stock { get; set; }
}
How do i get my get request to return my stock and Issue in my Json?
when i try add some value at Post method the operator was rejected with message error The requested resource does not support http method 'POST' .
Employee Class :
public class Employee
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public decimal sallary { get; set; }
public int Age { get; set; }
public Department Department { get; set; }
}
Department Class :
public class Department
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public ICollection<Employee> Employee { get; set; }
}
Output Of Employee Json :
[
{
"Id": 1,
"Name": "ibrahim",
"sallary": 6200,
"Age": 20,
"Department": {
"Id": 3,
"Name": "IOS",
"Employee": []
}
},
{
"Id": 2,
"Name": "ibrahimmmm",
"sallary": 6200,
"Age": 20,
"Department": {
"Id": 2,
"Name": "android",
"Employee": []
}
}
]
Output Of Department Json :
[
{
"Id": 1,
"Name": "design",
"Employee": []
},
{
"Id": 2,
"Name": "android",
"Employee": [
{
"Id": 2,
"Name": "ibrahimmmm",
"sallary": 6200,
"Age": 20
}
]
},
{
"Id": 3,
"Name": "IOS",
"Employee": [
{
"Id": 1,
"Name": "ibrahim",
"sallary": 6200,
"Age": 20
}
]
}
]
Method post Of Employee class :
public IHttpActionResult Post(Employee employee, int DepartmentId)
{
if (ModelState.IsValid)
{
var _department = db.Department.Find(DepartmentId);
employee.Department = _department;
db.Employee.Add(employee);
db.SaveChanges();
return Ok(employee);
}
return BadRequest(ModelState);
}
Method Get Of Employee class :
public IEnumerable<Employee> Get()
{
return db.Employee.Include(m => m.Department).ToList();
}
Method post Of Department class :
public IHttpActionResult Post(Department dep) {
if (ModelState.IsValid)
{
db.Department.Add(dep);
db.SaveChanges();
return Ok(dep);
}
return BadRequest(ModelState);
}
Method Get Of Department class :
public IEnumerable<Department> Get() {
var a = db.Department.Include(e => e.Employee).ToList();
return a;
//return db.Department.Include(item => item.Employee).ToList();
}
Just because you call the method Post, it doesn't mean that it will accept HTTP POST method. You need to decorate with [HttpPost] attribute.
GET is the default; so you don't have to decorate Get methods - but I consider it to be good style to put [HttpGet] as well.
Note, that you will probably get other errors, regarding submitted data; but at least the system will find a method that will respond to your request...
One more note - it is very unusual to put HTTP methods in model classes - that's what you have controllers for. So you may not even be able decorate Get/Post methods, if they are really in Department/Employee classes
UPDATE: Probably the last paragraph (Get/Post in Model class, rather than in controller) is the root cause of the problem!
I have a jquery data table in which i want to show a summarise report generated from sql query, but i am not able to do it, it shows error in the query. The summarise report consist of all month name and number of entries in every month.
Error:
System.Data.Entity.Core.EntityCommandExecutionException: 'The data reader is incompatible with the specified 'DHIFeedbackModel.FeedBack'. A member of the type, 'FeedbackUserName', does not have a corresponding column in the data reader with the same name.'
public ActionResult LoadData()
{
using (DHIFeedbackEntities2 Ms = new DHIFeedbackEntities2())
{
//var summary = Ms.FeedBacks.SqlQuery("select * from [DHIFeedback].[dbo].[FeedBack]").ToList<FeedBack>();
var summary = Ms.FeedBacks.SqlQuery(
#"SELECT *
FROM
(
SELECT
YEAR([FeedBackDate])[Year],DATENAME(MONTH, [FeedBackDate])[Month],
COUNT(1)[FeedbackID]
FROM
[DHIFeedback].[dbo].[FeedBack]
GROUP BY
YEAR([FeedBackDate]
),
DATENAME(MONTH, [FeedBackDate])) AS Monthlyupdate
PIVOT(SUM([FeedbackID]) FOR Month IN([January],[February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December])) AS MNamePivot
order by 1,2"
).FirstOrDefault<FeedBack>();
return Json(new { data = summary }, JsonRequestBehavior.AllowGet);
}
}
and the javascript:
$(document).ready(function () {
$('#Summary').DataTable({
"processing": true,
"ajax": {
"url": "/Summary/LoadData",
"type": "GET",
"datatype": "json",
},
"lengthMenu": [
[5, 10, 25, 50, 100, -1],
[5, 10, 25, 50, 100, "All"]
],
"autoWidth": true,
"responsive": true,
"lengthChange": true,
"ordering": true,
"fnRowCallback": function (nRow, aData, iDisplayIndex) {
var oSettings = this.fnSettings();
$("td:first", nRow).html(oSettings._iDisplayStart + iDisplayIndex + 1);
return nRow;
},
"columns": [
{ "data":"Year", "autoWidth": true },
{ "data":"January", "autoWidth": true },
{ "data":"February", "autoWidth": true },
{ "data":"March", "autoWidth": true },
{ "data":"April", "autoWidth": true },
{ "data":"May", "autoWidth": true },
{ "data":"June", "autoWidth": true },
{ "data":"July", "autoWidth": true },
{ "data":"August", "autoWidth": true },
{ "data":"September", "autoWidth": true },
{ "data":"October", "autoWidth": true },
{ "data":"November", "autoWidth": true },
{ "data":"December", "autoWidth": true }
]
});
});
public partial class FeedBack
{
public int FeedbackID { get; set; }
public string FeedbackUserName { get; set; }
public string FeedBackUserEmailID { get; set; }
public string FeedBackComment { get; set; }
public string Designation { get; set; }
public string Organization { get; set; }
public string ContactNo { get; set; }
public string City { get; set; }
public Nullable<System.DateTime> FeedBackDate { get; set; }
public Nullable<double> IsPublished { get; set; }
public string Reply { get; set; }
public Nullable<double> IsReplied { get; set; }
public Nullable<System.DateTime> ReplyDate { get; set; }
public string ReplyBy { get; set; }
public string Sector { get; set; }
public Nullable<int> Status { get; set; }
public int Year { get; set; }
public int January { get; set; }
public int February { get; set; }
public int March { get; set; }
public int April { get; set; }
public int May { get; set; }
public int June { get; set; }
public int July { get; set; }
public int August { get; set; }
public int September { get; set; }
public int October { get; set; }
public int November { get; set; }
public int December { get; set; }
public string Monthlyupdate { get; set; }
public string Month{ get; set; }
[NotMapped]
public List<FeedBack> FeedBackCollection { get; set; }
the error means that the ORM is expecting a resultset comprising each and every property of FeedBacks including the one named FeedbackUserName
So you need to edit the select clause of your sql to return all the expected columns.
or you may use
Ms.Database.SqlQuery<SomeType>(
"your query here").ToList();
where SomeType is :
public class SomeType {
public int Year {get; set;}
//... and/or all the pivoted columns
}
First please start from picture i have attached the json output view. On picture you will see i was able to assign value only to the root level objects but on child level i failed to assign value properly which i need. My main goal is get output exactly like Json code bellow. How can i fix my controller to get exactly example json type output from JavaScriptSerializer?
Controller:
var root = new RootObject();
root.name = "Jan Kowalski";
root.email = "jan.kowalski#wp.pl";
root.dayOfCycle = "10";
//root.tags.Add(new Tag
//{
// tagId = "Xw",
//});
//root.scoring = 25;
//root.customFieldValues.Add(new CustomFieldValue
//{
// customFieldId = "n",
// //value = "white", value should be list
//});
root.ipAddress = "89.206.36.193";
var camp = new Campaign();
camp.campaignId = "jf7e3jn";
var jsBody = new JavaScriptSerializer().Serialize(root);
Model class:
public class Campaign
{
public string campaignId { get; set; }
}
public class Tag
{
public string tagId { get; set; }
}
public class CustomFieldValue
{
public string customFieldId { get; set; }
public List<string> value { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string email { get; set; }
public string dayOfCycle { get; set; }
public Campaign campaign { get; set; }
public List<Tag> tags { get; set; }
public int scoring { get; set; }
public List<CustomFieldValue> customFieldValues { get; set; }
public string ipAddress { get; set; }
}
Json body i want from JavaScriptSerializer:
{
"name": "Jan Kowalski",
"email": "jan.kowalski#wp.pl",
"dayOfCycle": "10",
"campaign": {
"campaignId": "jf7e3jn"
},
"tags": [
{
"tagId": "Xw"
},
{
"tagId": "Nn"
}
],
"scoring": 25,
"customFieldValues": [
{
"customFieldId": "n",
"value": [
"white"
]
}
],
"ipAddress": "89.206.36.193"
}
As commented already, for the sake of completeness:
Missing: root.campaign = camp; just before creation of jsBody
Missing root.tags = new List<Tag>(); to prevent Null Reference Exception, just before root.tags.Add is executed
I am new in ASP.Net and MVC5 programming,in fact I have a problem,I have this Class "Student":
namespace Project.Entities.Models
{
public partial class Student : BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
[ForeignKey("ClassId")]
public virtual Class Class { get; set; }
public Int64 ClassId { get; set; }
[ForeignKey("ImageId")]
public virtual Image Image { get; set; }
public Int64 ImageId { get; set; }
public virtual List<Mark> Marks { get; set; }
public virtual List<Punishment> Punishments { get; set; }
public Student()
{
Marks = new List<Mark>();
Punishments = new List<Punishment>();
}
}
Class "Mark":
namespace SMA.Entities.Models
{
public partial class Mark : BaseEntity
{
public int Score { get; set; }
public string Note { get; set; }
[ForeignKey("StudentId")]
public virtual Student Student { get; set; }
public Int64 StudentId { get; set; }
}
}
I want to get the Marks of each Student,but I don't know How,
this is what I get in JSON result:
[
{
FirstName: "Student ",
LastName: "1",
Class: null,
ClassId: 1,
Image: null,
ImageId: 1,
Marks: [ ],
Punishments: [ ],
Id: 1,
ObjectState: 0
},
{
FirstName: "Student ",
LastName: "2",
Class: null,
ClassId: 2,
Image: null,
ImageId: 2,
Marks: [ ],
Punishments: [ ],
Id: 2,
ObjectState: 0
}
]
so please,have you any idea about,how can I access the Marks data for each Student
thanks for help
Assuming that you have an Id field in your Student entity that is the primary key (you didn't show it in the question, but I assume it was omitted), try changing this:
public virtual List<Mark> Marks { get; set; }
public virtual List<Punishment> Punishments { get; set; }
to
public virtual ICollection<Mark> Marks { get; set; }
public virtual ICollection<Punishment> Punishments { get; set; }