Cannot deserialize a JSON string using .NET Core - .net-core

I have recently switched to .NET Core and I am having trouble deserializing the following JSON string into this object. Usually works like a charm using Newtonsoft.
public class smDesktopSearchResultsVM
{
public smDesktopSearchResultsVM()
{
this.indexEventVMs = new List<indexEventVMLite>();
}
public int page { get; set; }
public int totalRecs { get; set; }
public int totalPages { get; set; }
public int? LinkGroupId { get; set; }
public List<indexEventVMLite> indexEventVMs { get; set; }
}
public class indexEventVMLite
{
public indexEventVMLite()
{
this.Event = new EventVMLite();
}
public EventVMLite Event { get; set; }
public int orderCount { get; set; }
public int sortOrder { get; set; }
public string pageImage { get; set; }
public string retinaPageImage { get; set; }
public int linkId { get; set; }
public int linkgroupId { get; set; }
public string pageURL { get; set; }
}
public class EventVMLite
{
public int WebsiteId { get; set; }
public int EventId { get; set; }
public string EventName { get; set; }
public string EventPassword { get; set; }
public DateTime EventDate { get; set; }
public DateTime? EventEndDate { get; set; }
public DateTime? EventExpires { get; set; }
public DateTime? DiscontinuedDate { get; set; }
public DateTime? forceDateDeleted { get; set; }
public bool EventReady { get; set; }
}
Here is the JSON sting:
{
"page": 1,
"totalRecs": 11,
"totalPages": 2,
"indexEventVMs": {
"Event": {
"WebsiteId": 5140,
"EventId": 14614,
"EventName": "Proofpix Elementary School",
"EventPassword": "proofpixelementarydemo",
"EventDate": "2021-08-30T16:00:00",
"EventEndDate": "2021-08-30T20:00:00",
"EventExpires": "2022-09-01T05:00:00",
"DiscontinuedDate": null,
"forceDateDeleted": null,
"EventReady": true
},
"orderCount": 5,
"sortOrder": 1,
"pageImage": "https://s3.us-east-1.wasabisys.com/usstandard.cdn.proofpix.com/websites/5140/PageMedia/266450/Descendants/1939278/680_9099_class-composite-7a.jpg",
"retinaPageImage": null,
"linkId": 354967,
"linkgroupId": 9527,
"pageURL": "https://jackblack.proofpix.com/proofpix-elementary-school/"
},
"LinkGroupId": 9527
}
Here is the error message:
The JSON value could not be converted to System.Collections.Generic.List`1[SortMagic_Desktop.indexEventVMLite]. Path: $.indexEventVMs | LineNumber: 0 | BytePositionInLine: 57.
What is funny is that Visual Studio has no problem parsing the JSON string to JSON when viewing the error data so it must be possible!

The problem can be in the List indexEventVMs a JSON list is [] but in the example it's a object {}.
So according to your JSON the classes would be something like this:
public class Object
{
public long Page { get; set; }
public long TotalRecs { get; set; }
public long TotalPages { get; set; }
public IndexEventVMs IndexEventVMs { get; set; }
public long LinkGroupId { get; set; }
}
public class IndexEventVMs
{
public Event Event { get; set; }
public long OrderCount { get; set; }
public long SortOrder { get; set; }
public Uri PageImage { get; set; }
public object RetinaPageImage { get; set; }
public long LinkId { get; set; }
public long LinkgroupId { get; set; }
public Uri PageUrl { get; set; }
}
public class Event
{
public long WebsiteId { get; set; }
public long EventId { get; set; }
public string EventName { get; set; }
public string EventPassword { get; set; }
public DateTimeOffset EventDate { get; set; }
public DateTimeOffset EventEndDate { get; set; }
public DateTimeOffset EventExpires { get; set; }
public object DiscontinuedDate { get; set; }
public object ForceDateDeleted { get; set; }
public bool EventReady { get; set; }
}
If you need that indexEventVMs receive a list you need to change from the json object {} to an array with object[{}].

You have to replace
public List<indexEventVMLite> indexEventVMs { get; set; }
with this
public indexEventVMLite indexEventVMs { get; set; }
but it is better to try this code
var json = ...your json
var result = JsonConvert.DeserializeObject<smDesktopSearchResultsVM>(json);
var resultSerialized =JsonConvert.SerializeObject(result);
result
{"page":1,"totalRecs":11,"totalPages":2,"indexEventVMs":{"Event":{"WebsiteId":5140,"EventId":14614,"EventName":"Proofpix Elementary School","EventPassword":"proofpixelementarydemo","EventDate":"2021-08-30T16:00:00-02:30","EventEndDate":"2021-08-30T20:00:00-02:30","EventExpires":"2022-09-01T05:00:00-02:30","DiscontinuedDate":null,"forceDateDeleted":null,"EventReady":true},"orderCount":5,"sortOrder":1,"pageImage":"https://s3.us-east-1.wasabisys.com/usstandard.cdn.proofpix.com/websites/5140/PageMedia/266450/Descendant/1939278/680_9099_class-composite-7a.jpg","retinaPageImage":null,"linkId":354967,"linkgroupId":9527,"pageURL":"https://jackblack.proofpix.com/proofpix-elementary-school"},"LinkGroupId":9527}
classes
public partial class smDesktopSearchResultsVM
{
[JsonProperty("page")]
public long Page { get; set; }
[JsonProperty("totalRecs")]
public long TotalRecs { get; set; }
[JsonProperty("totalPages")]
public long TotalPages { get; set; }
[JsonProperty("indexEventVMs")]
public IndexEventVMs IndexEventVMs { get; set; }
[JsonProperty("LinkGroupId")]
public long LinkGroupId { get; set; }
}
public partial class IndexEventVMs
{
[JsonProperty("Event")]
public Event Event { get; set; }
[JsonProperty("orderCount")]
public long OrderCount { get; set; }
[JsonProperty("sortOrder")]
public long SortOrder { get; set; }
[JsonProperty("pageImage")]
public Uri PageImage { get; set; }
[JsonProperty("retinaPageImage")]
public object RetinaPageImage { get; set; }
[JsonProperty("linkId")]
public long LinkId { get; set; }
[JsonProperty("linkgroupId")]
public long LinkgroupId { get; set; }
[JsonProperty("pageURL")]
public Uri PageUrl { get; set; }
}
public partial class Event
{
[JsonProperty("WebsiteId")]
public long WebsiteId { get; set; }
[JsonProperty("EventId")]
public long EventId { get; set; }
[JsonProperty("EventName")]
public string EventName { get; set; }
[JsonProperty("EventPassword")]
public string EventPassword { get; set; }
[JsonProperty("EventDate")]
public DateTimeOffset EventDate { get; set; }
[JsonProperty("EventEndDate")]
public DateTimeOffset EventEndDate { get; set; }
[JsonProperty("EventExpires")]
public DateTimeOffset EventExpires { get; set; }
[JsonProperty("DiscontinuedDate")]
public object DiscontinuedDate { get; set; }
[JsonProperty("forceDateDeleted")]
public object ForceDateDeleted { get; set; }
[JsonProperty("EventReady")]
public bool EventReady { get; set; }
}

Related

Trying to recreate a solution given for a question, need a little assistance

Trying to recreate a solution given for ASP.NET MVC - Taking search criteria as input, and displaying the results, in the same View?, but not sure where to find the querymanager that derloopkat uses in his example.
[HttpPost]
public ActionResult Query(FormQueryModel model)
{
var queryManager = new QueryManager(model);
model.QueryResults = queryManager.GetResults();
return View(model);
}
My ViewModels
public class PartRequestInfoSearch
{
public int? Building { get; set; }
public int? PartType { get; set; }
public int? PartStatus { get; set; }
public Nullable<System.DateTime> tmpStartDate { get; set; }
public Nullable<System.DateTime> tmpEndDate { get; set; }
public int PageSize { get; set; }
public List<RequestedPartInfo> RequestedPartInfos { get; set; }
public PartRequestInfoSearch()
{
this.RequestedPartInfos = new List<RequestedPartInfo>();
}
}
}
public class RequestedPartInfo
{
public int idPartRequest { get; set; }
public string Building { get; set; }
public string RequestNumber { get; set; }
public string PartNumber { get; set; }
public string VendorPartNumber { get; set; }
public string PartDescription { get; set; }
public int StockQTY { get; set; }
public int RequestQTY { get; set; }
public int ShippedQTY { get; set; }
public string PartStatus { get; set; }
}

automapping 1:1 mvc unmapped members found

I am trying to use automapper to map between my entites db class and my view model. They have the same exact prop names but i get the error thrown saying unmapped members found. From what I understand if you have 1:1 Relationship you do not have to do the manual mapping in the config file. what am I missing here?
product class
public class product
{
public int id { get; set; }
public string sku { get; set; }
public string ISBN { get; set; }
public string itemName { get; set; }
public int numberCds { get; set; }
public string description { get; set; }
public string category { get; set; }
public double price { get; set; }
public double weight { get; set; }
public int stock { get; set; }
public int stockAlert { get; set; }
public string salesTax { get; set; }
public string imgURL { get; set; }
public string videoURL { get; set; }
public int views { get; set; }
public string instantDownload { get; set; }
public string downloadLink { get; set; }
public int active { get; set; }
public string addedBy { get; set; }
public DateTime addedTime { get; set; }
public string updatedBy { get; set; }
public DateTime updatedTime { get; set; }
}
entites class
public partial class newProduct
{
public int id { get; set; }
public string sku { get; set; }
public string ISBN { get; set; }
public string itemName { get; set; }
public Nullable<int> numberCds { get; set; }
public string description { get; set; }
public string category { get; set; }
public double price { get; set; }
public Nullable<double> weight { get; set; }
public Nullable<int> stock { get; set; }
public Nullable<int> stockAlert { get; set; }
public string salesTax { get; set; }
public string imgURL { get; set; }
public string videoURL { get; set; }
public Nullable<int> views { get; set; }
public string instantDownload { get; set; }
public string downloadLink { get; set; }
public int active { get; set; }
public string addedBy { get; set; }
public Nullable<System.DateTime> addedTime { get; set; }
public string updatedBy { get; set; }
public Nullable<System.DateTime> updatedTime { get; set; }
}
Mapping Config
public static void RegisterMaps()
{
AutoMapper.Mapper.Initialize(config =>
{
config.CreateMap<product, newProduct>();
config.CreateMap<newProduct, product>();
});
}
and the controller
public ActionResult Index()
{
using (StoreEntities db = new StoreEntities())
{
var results = (from p in db.newProducts select p).Where(a => a.active == 1);
var products = AutoMapper.Mapper.Map<product>(results);
return View(products);
}

Cannot save entity one to one EF mvc 5

I am trying to insert a new record into database, no errors, a new record is not created in Applicant and ApplicantNotification table. Not sure what I am doing wrong?
Applicant
[Index]
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ApplicantID { get; set; }
[Required]
public string ApplicantTitle { get; set; }
[Required]
public string Firstname { get; set; }
[Required]
public string Lastname { get; set; }
[Required]
public string Address { get; set; }
[Required]
public string Address1 { get; set; }
[Required]
public string Address2 { get; set; }
[Required]
public string Address3 { get; set; }
[Required]
public string Postcode { get; set; }
[Required]
public string CaseReference { get; set; }
[DataType(DataType.Date)]
public DateTime DateOfBirth { get; set; }
/*Spouse*/
public string SpouseTitle { get; set; }
public string SpouseFirstname { get; set; }
public string SpouseLastname { get; set; }
public string SpouseAddress { get; set; }
public string SpouseAddress1 { get; set; }
public string SpouseAddress2 { get; set; }
public string SpouseAddress3 { get; set; }
public string SpousePostcode { get; set; }
ApplicantNotification
[Index]
[Key, Column("ApplicantID"), ForeignKey("Applicant")]
public int ApplicantNotificationID { get; set; }
public bool FirstNotification { get; set; }
public bool SecondtNotification { get; set; }
public bool ThirdNotification { get; set; }
public bool FinalNotification { get; set; }
public DateTime ReminderDate { get; set; }
public int ReminderFrequency { get; set; }
[DataType(DataType.Date)]
public DateTime? FirstNotificationDate { get; set; }
[DataType(DataType.Date)]
public DateTime? SecondNotificationDate { get; set; }
[DataType(DataType.Date)]
public DateTime? ThirdNotificationDate { get; set; }
public bool IsArchive { get; set; }
public virtual Applicant Applicant { get; set; }
ViewModel
public int ApplicantID { get; set; }
[Required]
public string ApplicantTitle { get; set; }
public string ApplicantFirstname { get; set; }
public string ApplicantLastname { get; set; }
public string ApplicantAddress { get; set; }
public string ApplicantAddress1 { get; set; }
public string ApplicantAddress2 { get; set; }
public string ApplicantAddress3 { get; set; }
public string ApplicantPostcode { get; set; }
[Required]
public string ApplicantCaseReference { get; set; }
[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ApplicantDateOfBirth { get; set; }
/*Spouse*/
public string SpouseTitle { get; set; }
public string SpouseFirstname { get; set; }
public string SpouseLastname { get; set; }
public string SpouseAddress { get; set; }
public string SpouseAddress1 { get; set; }
public string SpouseAddress2 { get; set; }
public string SpouseAddress3 { get; set; }
public string SpousePostcode { get; set; }
/*Notification*/
public int ApplicantNotificationID { get; set; }
public bool FirstNotification { get; set; }
public bool SecondNotification { get; set; }
public bool ThirdNotification { get; set; }
public bool FinalNotification { get; set; }
public DateTime? ReminderDate { get; set; }
Create Method:
// POST: Applicant/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ApplicantNotificationViewModel model)
{
var applicant = new Applicant();
var applicantNotification = new ApplicantNotification();
if (ModelState.IsValid)
{
SetApplicant(model, applicant);
SetApplicantNotification(model, applicantNotification);
using (var context = new WorkSmartContext())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
db.Applicants.Add(applicant);
context.SaveChanges();
db.ApplicantNotifcations.Add(applicantNotification);
context.SaveChanges();
dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
return RedirectToAction("Index");
}
}
return View(model);
}
Thanks for the suggestions in the comments.
It appears, if the datetime column is set to allow null, then the datetime either has to be set to null or set to the correct format in order for sql datetime to work. Otherwise it throws the
"The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\The statement has been terminated."
https://stackoverflow.com/questions/4608734/the-conversion-of-a-datetime2-data-type-to-a-datetime-data-type-resulted-in-an-o
I set the dates to null in my Entity objects, and entered a new entry to the database.

Non lazy loading

i have a model looks like this.
public class TradeModel
{
public int id { get; set; }
public BaseProductModel baseProduct { get; set; }
public string productDescription { get; set; }
public List<byte[]> images { get; set; }
public int price { get; set; }
// Date infos
public DateTime estimatedShippingDate { get; set; }
}
What i want to do is. when i call post request i want to send an id of an existing baseProduct not the entire baseProductForm and that being created.
ive tried
[Required]
public int baseProductId { get; set; }
[ForeignKey("baseProductId")]
public virtual BaseProductModel baseProduct { get; set; }
something like this, but seems to be not working.
any possible solutions?
Your model:
public class TradeModel
{
public int id { get; set; }
public int baseProductId { get; set; }
public virtual BaseProductModel baseProduct { get; set; }
public string productDescription { get; set; }
public List<byte[]> images { get; set; }
public int price { get; set; }
// Date infos
public DateTime estimatedShippingDate { get; set; }
}
Your ViewModel:
public class TradeViewModel
{
public int id { get; set; }
public int baseProductId { get; set; }
public string productDescription { get; set; }
public List<byte[]> images { get; set; }
public int price { get; set; }
// Date infos
public DateTime estimatedShippingDate { get; set; }
}
Now you can pass only the baseProductId:
public IActionResult(TradeViewModel model)
{
// Your form will contain only the id anyway so the method below should work.
// Replace that with your actual context
//dbcontext.Trades.Add(new TradeModel { ... });
}

Retrieving twitter with json

I'm having trouble with parsing a twitter flow, this code is returning this error message:
No parameterless constructor defined for type of
'System.Collections.Generic.IEnumerable`1[[Xxxx.Website.Templates.WidgetViews.Tweet,
Dolphin, Version=1.0.4801.24288, Culture=neutral,
PublicKeyToken=null]]'.
I would very much appreciate your help!
public partial class TwitterWidgetView
{
protected override void OnLoad(System.EventArgs e)
{
string listName = "sas";
string twitterListPath = "https://search.twitter.com/search.json?q=" + listName;
WebClient wc = new WebClient();
var json = wc.DownloadString(twitterListPath);
JavaScriptSerializer ser = new JavaScriptSerializer();
var tweetList = ser.Deserialize<IEnumerable<Tweet>>(json);
}
}
public class Metadata
{
public string result_type { get; set; }
}
public class Tweet
{
public Tweet()
{}
public string created_at { get; set; }
public string from_user { get; set; }
public int from_user_id { get; set; }
public string from_user_id_str { get; set; }
public string from_user_name { get; set; }
public object geo { get; set; }
public object id { get; set; }
public string id_str { get; set; }
public string iso_language_code { get; set; }
public Metadata metadata { get; set; }
public string profile_image_url { get; set; }
public string profile_image_url_https { get; set; }
public string source { get; set; }
public string text { get; set; }
public string to_user { get; set; }
public int to_user_id { get; set; }
public string to_user_id_str { get; set; }
public string to_user_name { get; set; }
public long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
}
public class RootObject
{
public RootObject()
{}
public double completed_in { get; set; }
public long max_id { get; set; }
public string max_id_str { get; set; }
public string next_page { get; set; }
public int page { get; set; }
public string query { get; set; }
public string refresh_url { get; set; }
public List<Tweet> results { get; set; }
public int results_per_page { get; set; }
public int since_id { get; set; }
public string since_id_str { get; set; }
}
Try using a list instead
var tweetList = ser.Deserialize<List<Tweet>>(json);

Resources