Newtonsoft.Json DeserializedObject wrong property values - json.net

using the example found here. https://www.newtonsoft.com/json/help/html/SerializingJSON.htm
deserializedProduct doesn't end up with the correct values. Can somebody point out what I'm missing please?
using Newtonsoft.Json;
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);
}
}
class Product
{
public string Name { get; internal set; }
public DateTime ExpiryDate { get; internal set; }
public decimal Price { get; internal set; }
public string[] Sizes { get; internal set; }
}
}

Properties need public getters and setters when deserializing in order to be able to set the values
class Product
{
public string Name { get; set; }
public DateTime ExpiryDate { get; set; }
public decimal Price { get; set; }
public string[] Sizes { get; set; }
}

Related

Why is my database table not loading using in ASP.NET Core

I am using a dbinitializer to try and seed data to a couple tables on my database. Everything seems to be ok except my Enrolls table doesn't want to populate. The Enrolls table holds all the List<> values of my Students and Courses. From that Enroll table I should be able to see which student is enrolled in which course. I am following a Microsoft docs tutorial but seem to hit a snag.
The thing is when I include the Enrolls property while creating an object in the initializer the entire database does not seed. However when I comment it out all tables except Enroll seed. I poked around a bit before I came here. Just hoping for a little guidance with some fresh pair of eyes as to where I should check/debug.
Truly hope I asked in a way that is understandable.
This is the DbInitializer:
public static class DbInitializer
{
public static void Initialize(StudentRegistrationContext context)
{
context.Database.EnsureCreated();
// Look for any students.
if (context.Students.Any() )
{
return; // DB has been seeded
}
var students = new Student[]
{
new Student
{
FirstName="A",
LastName="B",
Address = new Address
{
HouseNumber = "19",
Street="A ",
City="C",
Country = "T",
Email="s",
PhoneNumber = "6"
},
**// Enrollments = new List<Enroll> { new Enroll { CourseID = 2, ID=1 } }**
},
},
};
foreach (Student s in students)
{
context.Students.Add(s);
}
context.SaveChanges();
var course = new Course[]
{
new Course{CourseName = "Introduction to Computer Hardware",CourseCode = "ITEC120", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{ CourseName = "Introduction to Operating Systems", CourseCode= "ITEC122", NoOfCredits = 3, Category = Category.COMPULSORY },
new Course{ CourseName = "Programming 1",CourseCode = "ITEC133", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{CourseName = "Human and Computer Interface Design", CourseCode = "ITEC229", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{CourseName = "Webpage Design", CourseCode = "ITEC240", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{CourseName = "Computer Networks Architecture and Protocol",
};
foreach (Course c in course)
{
context.Course.Add(c);
}
context.SaveChanges();
var teacher = new Advisor[]
{
new Advisor{
FirstName="Teacher",
LastName="One",
Address = new Address{ HouseNumber = "123456",
Street="Teacher Street",
City="College City",
Country = "Trinidad",
Email="teacher#gmail.com",
PhoneNumber = "5648965"
},
Department="Department1",
Specialization=Category.ISD
},
};
foreach (Advisor t in teacher)
{
context.Advisor.Add(t);
}
context.SaveChanges();
var enroll = new Enroll[]
{
new Enroll{CourseID = 2, ID =2 },
};
foreach (Enroll e in enroll)
{
context.Enroll.Add(e);
}
context.SaveChanges();
}
}
My model classes:
public class Enroll
{
public int ID { get; set; }
public int CourseID { get; set; }
public Student Student { get; set; }
public Course Course { get; set; }
// public DateTime RegistrationDate { get; set; }
}
public class Student : Person
{
// public List<Course> Attends { get; set; }
public DateTime RegistrationDate { get; set; }
public List<Enroll> Enrollments { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public string CourseCode { get; set; }
public double NoOfCredits { get; set; }
public Category Category { get; set; }
public List<Enroll> Enrollments { get; set; }
}
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
}
So I figured out my issues. It was a mixture of ...
Editing the OnModelCreating function in the context
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Enroll>()
.HasOne(s => s.Student)
.WithMany(en => en.Enrollments)
.HasForeignKey(fk => fk.ID);
modelBuilder.Entity<Enroll>()
.HasOne(s => s.Course)
.WithMany(en => en.Enrollments)
.HasForeignKey(fk => fk.CourseID);
}
....and making my collection properties virtual:
public class Student : Person
{
public DateTime RegistrationDate { get; set; }
public virtual List<Enroll> Enrollments { get; set; }
}
public class Enroll
{
public int ID { get; set; }
public int CourseID { get; set; }
public virtual Student Student { get; set; }
public virtual Course Course { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public string CourseCode { get; set; }
public double NoOfCredits { get; set; }
public Category Category { get; set; }
public virtual List<Enroll> Enrollments { get; set; }
}
Thanks guys

How to add JObject to Entity Framework as an object

I have a list of variables representing deserlialized json jobjects that I would like to add them to the entity database. How can I do this?
The solution attempted so far:
var obj = JsonConvert.DeserializeObject<dynamic>(strtest);
foreach (var item in obj.results)
{
db.ReedAPIModels.Add(item);
db.SaveChanges();
}
Model class represents the database:
public class APIModel
{
[Key]
public int jobId { get; set; }
public int employerId { get; set; }
public string employerName { get; set; }
public string employerProfileId { get; set; }
public string employerProfileName { get; set; }
public string jobTitle { get; set; }
public string locationName { get; set; }
public int minimumSalary { get; set; }
public int maximumSalary { get; set; }
public string currency { get; set; }
public string expirationDate { get; set; }
public string date { get; set; }
public string jobDescription { get; set; }
public int applications { get; set; }
public string jobUrl { get; set; }
}
API Results
{
"results": [
{
"jobId": 39650785,
"employerId": 375315,
"employerName": "Spectrum IT Recruitment (South)",
"employerProfileId": null,
"employerProfileName": null,
"jobTitle": "Senior Front End Developer",
"locationName": "Reading",
"minimumSalary": 60000,
"maximumSalary": 70000,
"currency": "GBP",
"expirationDate": "17/01/2020",
"date": "03/01/2020",
"jobDescription": " Senior Front End Developer - Reading, Berkshire Senior Front End Developer required by a growing company based in Reading, Berkshire. The company are looking to recruit a Senior Front End Developer to join their expanding development team to work on the full design and development lifecycle of new products. The successful Senior Front End Developer will have lots of opportunities for development of both techni... ",
"applications": 0,
"jobUrl": "https://www.reed.co.uk/jobs/senior-front-end-developer/39650785"
}
],
"ambiguousLocations": [],
"totalResults": 9007
}
Also, I have tried to use ToObject method
First of all you need a RootObject model which can be created by this website:
http://json2csharp.com/
RootObject datalist = JsonConvert.DeserializeObject<RootObject>(strtest);
foreach (var item in datalist.results)
{
db.APIModels.Add(item);
db.SaveChanges();
}
You should Add APIModel instead of ReedAPIModels.
Your can try this way
var apiResult = JsonConvert.DeserializeObject<dynamic>(strtest);
foreach (var item in apiResult.results)
{
db.APIModel.Add(item);
db.SaveChanges();
}

cannot convert type dto to type Ienumerable

I am creating an asp.net core web.api and need to return DTO object from Ienumerable method. I am getting error in the controller get method saying cannot convert DTO to type Ienumerable
namespace Products.DTO
{
public class Products
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public DateTime Available { get; set; }
public decimal Price { get; set; }
}
}
namespace Products.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
[HttpGet]
public ActionResult<IEnumerable<DTO.Products>> GetProducts()
{
return new DTO.Products
{
Id = 1, Name = "Cricket bat", Available = DateTime.Now, Code = "AC122333", Price = 1223.23M
};
}
}
}
Try this way
return new DTO.Products[]{
DTO.Products { Id = 1, Name = "Cricket bat", Available = DateTime.Now, Code = "AC122333", Price = 1223.23M }
};

Serialize JSON in ASP.NET

I am new in ASP.NET world and I am trying to achieve following.
I need to serialize API of this format
{
"results": {
"profile": {
"firstname": "John,
"lastname": "Newman",
},
"credit": {
"amount": 30
}
}
}
The problem is that I don't know how to model my data. I need a results object, which contains 2 other objects (profile and credit). You can see some sample code below.
public class Results
{
public class Data {
public Profile profile { get; set; }
public Credit credit {get; set; }
}
public class Profile {
public String firstname {get; set; }
public String lastname { get; set; }
}
public class Credit {
public int amount { get; set; }
}
}
static void Main(string[] args)
{
Results results= new Results
{
Data = new Data{
Profile = new Profile {
firstname = "John",
lastname = "Newman"
},
Credit = new Credit {
balance = "30"
}
}
};
string json = JsonConvert.SerializeObject(results);
Console.WriteLine(json);
}
The error I get is "Member Data cannot be initialized. It is not a field or property. What am I doing wrong?
Try this instead:
public class Profile
{
public String firstname { get; set; }
public String lastname { get; set; }
}
public class Credit
{
public int amount { get; set; }
}
public class Result
{
public Profile profile { get; set; }
public Credit credit { get; set; }
}
public class Wrapper
{
public Result results { get; set; }
}
static void Main(string[] args)
{
var wrapper = new Wrapper
{
results = new Result
{
profile = new Profile
{
firstname = "John",
lastname = "Newman"
},
credit = new Credit
{
amount = 30
}
}
};
string json = JsonConvert.SerializeObject(wrapper);
Console.WriteLine(json);
}
Try this :
static void Main(string[]args) {
Base results = new Base() {
Results = new Results() {
profile = new Profile() {
firstname = "John",
lastname = "Newman"
},
credit = new Credit() {
amount = 30
}
}
};
string json = JsonConvert.SerializeObject(results);
Console.WriteLine(json);
Console.ReadLine();
}
public class Base {
public Results Results {get;set;}
}
public class Results{
public Profile profile {get;set;}
public Credit credit {get;set;}
}
public class Profile{
public String firstname {get;set;}
public String lastname {get;set;}
}
public class Credit{
public int amount {get;set;}
}
Class Base wraps Results class to get the required JSON structure.

Insert multiple values from text box to the data base using the list<string>

This is the required image, I want to insert multiple value through Name, Employee Code and E-mail Id, by submit button which is in this page.
My database contains following field Id(primary key),Name (varchar 50),Employee Code (varchar 50), E-mail Id (varchar 50).
In the data layer, I code as following:
public static bool AddParticipantlistemployeecode(DimensionQuestion dimension)
{
bool result;
using (var helper = new DbHelper())
{
_cmdtext = "sp_NewGeneratedUniqueCode";
var success = new SqlParameter("#Success", SqlDbType.Bit, 1, ParameterDirection.Output, true, 0, 0,
"Result", DataRowVersion.Default, 0);
foreach (string s in dimension.CandidateName)
{
if (s.Trim().Length > 0)
{
var parameter = new[]
{
// new SqlParameter("#CompanyName",dimension.CompanyName ),
new SqlParameter("#CandidateName",s ),
new SqlParameter("#EmployeeCode",s ),
new SqlParameter("#EmailId",s ),
success,
};
helper.ExecuteScalar(_cmdtext, CommandType.StoredProcedure, parameter);
}
}
result = (bool)success.Value;
}
return result;
}
In the Model layer:
using System.Text;
using System.Collections.Generic;
namespace Cengrow.Survey.Core.Model
{
public class DimensionQuestion
{
public string CompanyName { get; set; }
// public string DimensionNumber { get; set; }
public List<string> CandidateName { get; set; }
public List<string> EmployeeCode { get; set; }
public List<string> EmailId { get; set; }
public int DimensionName { get; set; }
public string Section { get; set; }
//public string Rating { get; set; }
public List<string> Questions { get; set; }
//public string Question2 { get; set; }
//public string Question3 { get; set; }
//public string Question4 { get; set; }
//public string Question5 { get; set; }
//public string Question6 { get; set; }
//public string Question7 { get; set; }
//public string Question8 { get; set; }
//public string Question9 { get; set; }
//public string Question10 { get; set; }
//public string Question11 { get; set; }
//public string Question12 { get; set; }
//public string Question13 { get; set; }
//public string Question14 { get; set; }
//public string Question15 { get; set; }
}
}
And finally in the business logic on the button click:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
FillObjects();
//if (InsertData.InsertCandidateCompany(_CandidateCompanyInformation ))
if (InsertData.AddParticipantlistemployeecode(_DimensionQuestion))
{
ShowMessage("Information is saved");
//Reset();
}
else
{
ShowMessage("Please try again");
}
}
finally
{
_DimensionQuestion = null;
}
}
private void FillObjects()
{
List<string> sp = new List<string>();
_DimensionQuestion = new Cengrow.Survey.Core.Model.DimensionQuestion();
// _DimensionQuestion.CompanyName = txtCompanyName.Text.Trim();
sp.Add(txtName1.Text.Trim());
sp.Add(txtName2.Text.Trim());
sp.Add(txtName3.Text.Trim());
sp.Add(txtName4.Text.Trim());
sp.Add(txtName5.Text.Trim());
sp.Add(txtName6.Text.Trim());
sp.Add(txtName7.Text.Trim());
sp.Add(txtName8.Text.Trim());
sp.Add(txtName9.Text.Trim());
sp.Add(txtName10.Text.Trim());
sp.Add(txtName11.Text.Trim());
sp.Add(txtName12.Text.Trim());
sp.Add(txtName13.Text.Trim());
sp.Add(txtName14.Text.Trim());
sp.Add(txtName15.Text.Trim());
sp.Add(txtName16.Text.Trim());
sp.Add(txtName17.Text.Trim());
sp.Add(txtName18.Text.Trim());
sp.Add(txtName19.Text.Trim());
sp.Add(txtName20.Text.Trim());
sp.Add(txtName21.Text.Trim());
sp.Add(txtName22.Text.Trim());
sp.Add(txtName23.Text.Trim());
sp.Add(txtName24.Text.Trim());
sp.Add(txtName25.Text.Trim());
_DimensionQuestion.CandidateName = sp;
sp.Add(txtEmployeeCode1.Text.Trim());
sp.Add(txtEmployeeCode2.Text.Trim());
sp.Add(txtEmployeeCode3.Text.Trim());
sp.Add(txtEmployeeCode4.Text.Trim());
sp.Add(txtEmployeeCode5.Text.Trim());
sp.Add(txtEmployeeCode6.Text.Trim());
sp.Add(txtEmployeeCode7.Text.Trim());
sp.Add(txtEmployeeCode8.Text.Trim());
sp.Add(txtEmployeeCode9.Text.Trim());
sp.Add(txtEmployeeCode10.Text.Trim());
sp.Add(txtEmployeeCode11.Text.Trim());
sp.Add(txtEmployeeCode12.Text.Trim());
sp.Add(txtEmployeeCode13.Text.Trim());
sp.Add(txtEmployeeCode14.Text.Trim());
sp.Add(txtEmployeeCode15.Text.Trim());
sp.Add(txtEmployeeCode16.Text.Trim());
sp.Add(txtEmployeeCode17.Text.Trim());
sp.Add(txtEmployeeCode18.Text.Trim());
sp.Add(txtEmployeeCode19.Text.Trim());
sp.Add(txtEmployeeCode20.Text.Trim());
sp.Add(txtEmployeeCode21.Text.Trim());
sp.Add(txtEmployeeCode22.Text.Trim());
sp.Add(txtEmployeeCode23.Text.Trim());
sp.Add(txtEmployeeCode24.Text.Trim());
sp.Add(txtEmployeeCode25.Text.Trim());
_DimensionQuestion.EmployeeCode = sp;
sp.Add(TextBox1.Text.Trim());
sp.Add(TextBox2.Text.Trim());
sp.Add(TextBox3.Text.Trim());
sp.Add(TextBox4.Text.Trim());
sp.Add(TextBox5.Text.Trim());
sp.Add(TextBox6.Text.Trim());
sp.Add(TextBox7.Text.Trim());
sp.Add(TextBox8.Text.Trim());
sp.Add(TextBox9.Text.Trim());
sp.Add(TextBox10.Text.Trim());
sp.Add(TextBox11.Text.Trim());
sp.Add(TextBox12.Text.Trim());
sp.Add(TextBox13.Text.Trim());
sp.Add(TextBox14.Text.Trim());
sp.Add(TextBox15.Text.Trim());
sp.Add(TextBox16.Text.Trim());
sp.Add(TextBox17.Text.Trim());
sp.Add(TextBox18.Text.Trim());
sp.Add(TextBox19.Text.Trim());
sp.Add(TextBox20.Text.Trim());
sp.Add(TextBox21.Text.Trim());
sp.Add(TextBox22.Text.Trim());
sp.Add(TextBox23.Text.Trim());
sp.Add(TextBox24.Text.Trim());
sp.Add(TextBox25.Text.Trim());
_DimensionQuestion.EmailId = sp;
}
The data is not coming proper into the database
You are adding the same value to all three parameters:
new SqlParameter("#CandidateName",s ),
new SqlParameter("#EmployeeCode",s ),
new SqlParameter("#EmailId",s
In all cases you are adding "s" which is CandidateName.
Edit: Candidate should be a class:
public class Candidate
{
public string Name { get; set; }
public string EmployeeCode { get; set; }
public string Email { get; set; }
public Candidate(string name, string code, string email)
{
this.Name = name;
this.EmployeeCode = code;
this.Email = email;
}
}
Then your DimensionQuestion should contain a
List<Candidate> Candidates
instead of
public List<string> CandidateName { get; set; }
public List<string> EmployeeCode { get; set; }
public List<string> EmailId { get; set; }
Then you FillObjects method add Candidate objects to the Candidates list
Candidates.Add(new Candidate(txtName1.Text.Trim(),
txtEmployeeCode1.Text.Trim(),
TextBox1.Text.Trim()));
Candidates.Add(new Candidate(txtName2.Text.Trim(),
txtEmployeeCode2.Text.Trim(),
TextBox2.Text.Trim()));
Finaly your data layer should be:
foreach (Candidate candidate in dimension.Candidates)
{
if (!String.IsNullOrEmpty(candidate.Name))
{
var parameter = new[]
{
// new SqlParameter("#CompanyName",dimension.CompanyName ),
new SqlParameter("#CandidateName",candidate.Name ),
new SqlParameter("#EmployeeCode",candidate.Code ),
new SqlParameter("#EmailId",candidate.Email ),
success,
};
helper.ExecuteScalar(_cmdtext, CommandType.StoredProcedure, parameter);
}
}

Resources