Newtonsoft serialization - json.net

I need some help with custom serialization using Newtonsoft Json (Json.Net). I have classes like below:
public class Person
{
[JsonProperty(PropertyName = "PersonName")]
public string Name { get; set; }
[JsonIgnore]
public int Age { get; set; }
public Address PersonAddress { get; set; }
}
public class Address
{
[JsonProperty(PropertyName = "Address1")]
public string Address1 { get; set; }
[JsonIgnore]
public string Address2 { get; set; }
[JsonProperty(PropertyName = "City")]
public string City { get; set; }
[JsonProperty(PropertyName = "State")]
public string State { get; set; }
[JsonIgnore]
public string Country { get; set; }
}
When I serialize the above class it should return output like below:
{
"PersonName":"Name",
"Address1":"Address1",
"City":"City",
"State":"state"
}
How can I do it using Newtonsoft?

You can create a third class as follows:
public class Rootobject
{
public string PersonName { get; set; }
public string Address1 { get; set; }
public string City { get; set; }
public string State { get; set; }
}
Then, an object out of it like this:
var rootObject = new Rootobject()
{
PersonName = person.Name,
Address1 = address.Address1,
City = address.City,
State = address.State
};
And finally serialize it using JsonCovert:
var result = JsonConvert.SerializeObject(rootObject);

Related

How to modify database having foreign key in asp.net?

I have two tables: SurveyOption and SurveyQuestion, in my DbModel.
public class SurveyOptions
{
[Key]
public Guid SurveyOptionId { get; set; }
public Guid? SurveyQuestionId { get; set; }
public int? Sequence { get; set; }
[MaxLength(50)]
public string OptionValue { get; set; }
[MaxLength(500)]
public string Description { get; set; }
public Guid? ImageId { get; set; }
}
public class SurveyQuestions
{
[Key]
public Guid SurveyQuestionsId { get; set; }
public Guid? SurveyMasterId { get; set; }
public int? Sequence { get; set; }
[MaxLength(1)]
public string QuestionType { get; set; }
[MaxLength(500)]
public string QuestionText { get; set; }
public bool? Required { get; set; }
public string ExplanationLink { get; set; }
}
SurveyQuestionId is the foreign key in SurveyOption. While making an update query I repeatedly get an error The INSERT statement conflicted with the FOREIGN KEY constraint "FK_SurveyOptions_SurveyQuestions". The conflict occurred in database "MCNITemp", table "dbo.SurveyQuestions", column 'SurveyQuestionsId'.
My ViewModel of SurveyQuestion consist of OptionList. In which each SurveyQuestion holds its own optionList of type List<SurveyOption> and questionList is of type List<SurveyQuestion>
My modify code is the following:
foreach (var question in questionList)
{
var options = question.OptionsList;
foreach (var option in options)
{
var optionData = _mcniDbContext.SurveyOptions.Where(e => e.SurveyOptionId == option.SurveyOptionId).FirstOrDefault();
if (optionData == null)
{
_mcniDbContext.SurveyOptions.Add(new SurveyOptions()
{
OptionValue = option.OptionValue,
Description = option.Description,
Sequence = option.Sequence,
SurveyOptionId = option.SurveyOptionId,
SurveyQuestionId = option.SurveyQuestionId
});
}
else
{
optionData.SurveyOptionId = option.SurveyOptionId;
optionData.SurveyQuestionId = option.SurveyQuestionId;
optionData.Sequence = option.Sequence;
optionData.OptionValue = option.OptionValue;
optionData.Description = option.Description;
_mcniDbContext.Entry(optionData).State = EntityState.Modified;
}
_mcniDbContext.SaveChanges();
}
var questionData = _mcniDbContext.SurveyQuestions.Where(e => e.SurveyQuestionsId == question.SurveyQuestionsId).FirstOrDefault();
questionData.SurveyQuestionsId = question.SurveyQuestionsId;
questionData.SurveyMasterId = surveyMasterId;
questionData.QuestionText = question.QuestionText;
questionData.QuestionType = question.QuestionType;
questionData.Required = question.Required;
_mcniDbContext.Entry(questionData).State = EntityState.Modified;
_mcniDbContext.SaveChanges();
}
In your model you have let EF know how relationships are working. Assuming you have not used Fluent Api for desribing same, your code can be like below (code has not been test):
public class SurveyOptions
{
[Key]
public Guid SurveyOptionId { get; set; }
[ForeignKey("SurveyQuestionId")]
public SurveyQuestion SurveyQuestion {get;set;}
public Guid? SurveyQuestionId { get; set; }
public int? Sequence { get; set; }
[MaxLength(50)]
public string OptionValue { get; set; }
[MaxLength(500)]
public string Description { get; set; }
public Guid? ImageId { get; set; }
}

Deserialize json without root object and 1 array ASP.NET MVC

I'm building a web application that's using a third parties API and I receive the json below
{
"CompanyID": 14585,
"CompanyName": "The Morgan Group Daytona, LLC",
"BillingAddressLine": "100 S Beach St #200",
"BillingAddressCity": "Daytona Beach",
"BillingAddressState": "Fl",
"BillingAddressPostCode": "32114",
"BillingCountryCode": "US",
"BillingAddress": "100 S Beach St #200\r\nDaytona Beach Fl 32114\r\nUNITED STATES",
"Phone": null,
"Fax": null,
"website": null,
"TaxNumber": null,
"Comments": null,
"CurrencyCode": "USD",
"DefaultTradingTermIDFK": 15,
"DateCreated": "2020-09-04T18:25:02",
"DateUpdated": "2020-09-04T18:25:02",
"Contacts": [
{
"ContactID": 13781,
"CompanyIDFK": 14585,
"CompanyName": null,
"Firstname": "Test",
"Lastname": "User",
"Email": "test#test.com",
"Phone": null,
"Mobile": "4075551234",
"PositionTitle": "Test Title",
"TimeZone": "Eastern Standard Time",
"DateCreated": "2020-09-07T02:21:10",
"DateUpdated": "2020-09-07T02:21:10"
}
]
}
All of the other json responses for the other API calls also do not have root objects. The goal is to use razor to display this information on the view. Whats the most efficient way to do so?
So far I've created this class file
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
but now i'm stuck on trying to figure out how to deserialize something like this? Whats the easiest way to do this. I can't seem to find any other post that matches this same set of circumstances.
When you get a blob of JSON, you can speed things up by going to https://json2csharp.com/ and have it convert it in to classes. For example, that blob returns this:
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public string Phone { get; set; }
public string Fax { get; set; }
public string website { get; set; }
public string TaxNumber { get; set; }
public string Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}
The classes it returns will sometimes have some small issues, for example, since your blob had a lot of null properties, it just converted them to object. I changed them to string.
Then you simply use Newtonsoft.Json to convert it:
using(var s = File.OpenRead(#"c:\users\andy\desktop\test.json"))
using(var sr = new StreamReader(s))
using(var jtr = new JsonTextReader(sr))
{
var obj = new JsonSerializer().Deserialize<Root>(jtr);
}
And you are finished:
ETA
You posted your code on getting this data and noticed you are using WebRequest. Just a heads up that WebRequest is legacy and you should be using HttpClient. This is how you download/deserialize with HttpClient:
private static readonly HttpClient _httpClient = new HttpClient();
private static async Task<Root> GetStuffFromThereAsync(string token)
{
using(var req = new HttpRequestMessage(HttpMethod.Get,
new Uri("https://www.example.com")))
{
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using (var resp = await _httpClient.SendAsync(req))
{
resp.EnsureSuccessStatusCode();
using (var s = await resp.Content.ReadAsStreamAsync())
using (var sr = new StreamReader(s))
using (var jtr = new JsonTextReader(sr))
{
return new JsonSerializer().Deserialize<Root>(jtr);
}
}
}
}
If it is still returning null, then there is a chance your models don't match.
You need to use the below the line with class I have mentioned :
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>("This is the your JSON string");
Class
public class Contact {
public int ContactID { get; set; }
public int CompanyIDFK { get; set; }
public object CompanyName { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public object Phone { get; set; }
public string Mobile { get; set; }
public string PositionTitle { get; set; }
public string TimeZone { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
}
public class Root {
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string BillingAddressLine { get; set; }
public string BillingAddressCity { get; set; }
public string BillingAddressState { get; set; }
public string BillingAddressPostCode { get; set; }
public string BillingCountryCode { get; set; }
public string BillingAddress { get; set; }
public object Phone { get; set; }
public object Fax { get; set; }
public object website { get; set; }
public object TaxNumber { get; set; }
public object Comments { get; set; }
public string CurrencyCode { get; set; }
public int DefaultTradingTermIDFK { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public List<Contact> Contacts { get; set; }
}

How to create a drop-down in asp.net core MVC from another Model with validation?

Model Class.cs
public class Class
{
public int ClassId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
[Required]
[Display(Name = "Class Name")]
public string ClassName { get; set; }
}
Model Subject.cs
public class Subject
{
public int SubjectId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
public string SubjectName { get; set; }
public int ClassId { get; set; }
public Class Class { get; set; }
}
ViewModel CreateSubjectViewModel.cs
public class CreateSubjectViewModel
{
public int SubjectId { get; set; }
[NotMapped]
public string EncryptedId { get; set; }
[Required]
[Display(Name = "Subject Name")]
public string SubjectName { get; set; }
public int ClassId { get; set; }
public int ClassesId { get; set; }
public virtual List<Class> Classes { get; set; }
}
Controller Code
[HttpGet]
public IActionResult CreateSubject()
{
List<Class> classList = _context.Classes.ToList();
ViewData["classList"] = classList.Select(x => new SelectListItem { Value = x.EncryptedId, Text = x.ClassName });
return View();
}
[HttpPost]
public IActionResult CreateSubject(CreateSubjectViewModel model)
{
if (ModelState.IsValid)
{
Subject newSubject = new Subject
{
//SubjectName = model.SubjectName,
//here code for store data in subject table
};
_cdsRepository.AddSubject(newSubject);
return RedirectToAction("ListClasses", "UDP");
}
return View(model);
}
How can I get data from Class.cs and show in drop-down with proper validation of drop-down on button click.
If everything is OK, then store data in Subject.cs with Class Id value.

ServiceStack, OrmLite Issue Saving Related Entities

I've searched for a while looking for a solution to this problem and haven't found anything.
I'm trying to POST a Client DTO and it's related Contacts DTOs to my ServiceStack web service but I'm getting an error. I've followed along with the OrmLite tests located here.
My DTOs:
public partial class Client {
[AutoIncrement]
public int ID { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public decimal? Latitude { get; set; }
public decimal? Longitude { get; set; }
public string HomePhoneAreaCode { get; set; }
public string HomePhoneExchange { get; set; }
public string HomePhoneNumber { get; set; }
public string HomeFaxAreaCode { get; set; }
public string HomeFaxExchange { get; set; }
public string HomeFaxNumber { get; set; }
public string KeyNumber { get; set; }
public string AlarmCode { get; set; }
public string GarageDoorCode { get; set; }
public string MyAPCUsername { get; set; }
public string MyAPCPassword { get; set; }
public bool IsActive { get; set; }
public string Notes { get; set; }
[Reference]
public List<Contact> Contacts { get; set; }
}
public partial class Contact {
[AutoIncrement]
public int ID { get; set; }
public int ClientID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string WorkPhoneAreaCode { get; set; }
public string WorkPhoneExchange { get; set; }
public string WorkPhoneNumber { get; set; }
public string MobilePhoneAreaCode { get; set; }
public string MobilePhoneExchange { get; set; }
public string MobilePhoneNumber { get; set; }
public bool CanSMS { get; set; }
public string PersonalEmail { get; set; }
public string WorkEmail { get; set; }
public string AlternateEmail { get; set; }
public int Ordinal { get; set; }
[Reference]
public Client Client { get; set; }
}
In my Service:
public int Post(Client client) {
Db.Save(client, references: true);
return client.ID;
}
And my test code:
var newClient = new Client {
Street = "1234 Any Avenue",
City = "Gorham",
State = "ME",
ZipCode = "22222",
HomePhoneAreaCode = "123",
HomePhoneExchange = "456",
HomePhoneNumber = "7890",
HomeFaxAreaCode = "098",
HomeFaxExchange = "765",
HomeFaxNumber = "4321",
KeyNumber = "99",
AlarmCode = "1234",
GarageDoorCode = "abcd",
IsActive = true,
Notes = "These are the notes for the new client.",
Contacts = new List<Contact>() {
new Contact { FirstName = "John", LastName = "Doe", PersonalEmail = "john.doe#gmail.com", CanSMS = true, Ordinal = 1 },
new Contact { FirstName = "Jane", LastName = "Smith", PersonalEmail = "jane.smith#gmail.com", CanSMS = false, Ordinal = 2 }
},
};
// POST entity
int newClientID = serviceClient.Post<int>(newClient);
The last line produces the error -
WebServiceException, message "Cant find 'ClientId' Property on Type 'Contact'"
I've tried different combinations of the Reference, References, and ForeignKey attributes to no avail.
Any help would be appreciated.
Thanks,
Jay

Cannot implicitly convert type 'System.Guid?' to 'DataContracts.Market'

I am getting the following error
Cannot implicitly convert type 'System.Guid?' to 'DataContracts.Market'
private CellSite MapEntityToCellSitePOCO(t_CellSite _cellsite)
{
CellSite cellsite= new CellSite();
cellsite.SiteId = _cellsite.SiteID;
cellsite.Market.MarketID = _cellsite.MarketId;
cellsite.Region.RegionId = _cellsite.RegionId;
return cellsite;
}
the following is my datacontracts file
public class CellSite
{
public Guid CellSiteID { get; set; }
public string SiteId { get; set; }
public Region Region { get; set; }
public Market Market { get; set; }
public Guid? ConstructionManager { get; set;}
}
This is market.cs
public class Market
{
public Guid? MarketID { get; set; }
public string OperatorMarketName { get; set; }
public string MarketName { get; set; }
public decimal AllOtherAmount { get; set; }
public decimal RawLandAmount { get; set; }
public decimal RenewalFee { get; set; }
public bool IsActive { get; set; }
}
there is a column MarketId in cellsite table which i want to bring on.how can i do that? I am new to entity frame work.
thanks in advance
You have to initialize your Market and Region properties first:
CellSite cellsite= new CellSite();
cellsite.SiteId = _cellsite.SiteID;
cellsite.Market = new Market();
cellsite.Market.MarketID = _cellsite.MarketId;
cellsite.Region = new Region();
cellsite.Region.RegionId = _cellsite.RegionId;

Resources