I am getting the json from the HttpClient Get Request. the result is deserializing every property except the Guid and Datetime. the Guid properties are parsing as {System.Guid} and date is parsing back as {System.DateTime}.
Web Request:
var json = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ICollection<UserEntity>>(json);
Json:
[{"Id":"5aee0750-6cd9-4d20-9fe9-1f7e23a4520b","MemberShipUserID":12346,
"Username":"Joshr","EmpName":"Josh","Password":"test123",
"Email":"nanidotnetdev#gmail.com","Phone":"1234567899",
"IsActive":true,"IsContractor":true,"RoleID":null,"ProfilePhotoID":null,
"CreatedDate":"2018-08-08T01:15:12.73",
"CreatedBy":"e4c6d172-3d14-4539-9fee-306b081dc3db","UpdatedDate":null,
"UpdatedBy":null,"LastLoginDate":null}]
UserEntity:
public class UserEntity
{
public Guid Id { get; set; }
public int? MemberShipUserID { get; set; }
public string Username { get; set; }
public string EmpName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public bool IsActive { get; set; }
public bool IsContractor { get; set; }
public Guid? RoleID { get; set; }
public string ProfilePhotoID { get; set; }
public DateTime CreatedDate { get; set; }
public Guid CreatedBy { get; set; }
public DateTime? UpdatedDate { get; set; }
public Guid? UpdatedBy { get; set; }
public DateTime? LastLoginDate { get; set; }
}
Am I missing any property declarations here? Please clarify.
Thanks
Related
This is the first time I have attempted to join information from one database to the other. I have a accounting database and a regular site database. Trying to keep them separate. I have a page that shows Transactions but am getting the information for a few of the columns from the regular database by way of Id's. Below is my Model. I am showing nothing in the fields for the items in the other database.
public class Transaction
{
[Key]
public Guid TransactionId { get; set; }
public string Description { get; set; }
public int? CompanyId { get; set; }
public Guid? VendorId { get; set; }
public string InCheckNumber { get; set; }
public string OutCheckNumber { get; set; }
public string InvoiceNumber { get; set; }
public string PurchaseOrderNumber { get; set; }
public Guid LedgerAccountId { get; set; }
public decimal? DebitAmount { get; set; }
public decimal? CreditAmount { get; set; }
public DateTime TransactionDate { get; set; }
public string ModifiedBy { get; set; }
public DateTime? ModifiedDate { get; set; }
public string SavedDocument { get; set; }
public DateTime CreatedDate { get; set; }
public string CreatedBy { get; set; }
public bool IsCredit { get; set; }
public bool IsDebit { get; set; }
public Guid Type { get; set; }
[ForeignKey("LedgerAccountId")]
public LedgerAccount LedgerAccount { get; set; }
[ForeignKey("CompanyId")]
public CompanyNames Company { get; set; }
[ForeignKey("VendorId")]
public Vendors Vendor { get; set; }
}
I have added the 'using' of the General.Entities to this model. Is there something else i need to add for this?
Thanks in advance.
UPDATE:
See Question - Link to answer of question
how i can solve this problem (serialized/ and deserialize JSON array and store and read from sql server)?
thank you
i created asp.net core api that connected to angular project and occurs problem when i want post json that contains json array(ingredient) :
{ "RecepieName": "3222",
"Ingredient": [ { "ingredientName": "43243", "value": "33", "measure": "" },
{ "ingredientName": "565" , "value": "3", "measure": "" }],
"CookingTime": 3,
"Level": "advance",
"ServingPerson": 3,
"RecepieAbstration": "good food",
"RecepieText": "",
"CreateDate": "2021-01-04T12:37:51.948",
"ModifiedDate": "2021-01-04T12:37:51.948" }
when i use postman for test I encounter this error :
postman error
you can see my model , dto and action post in controller :
Model :
public class Recepie
{
[Key]
public int ID { get; set; }
[Required]
public string RecepieName { get; set; }
[Required]
public string Ingredient { get; set; } // include ingredientName / value / measure array
[Required]
public int CookingTime { get; set; }
[Required]
public string Level { get; set; }
[Required]
public int ServingPerson { get; set; }
[Required]
public string RecepieAbstration { get; set; }
[Required]
public string RecepieText { get; set; }
[Required]
public string NutritionalInformation { get; set; }
[Required]
public string Tags { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
DTO : RecepieCreateDto
public class RecepieCreateDto
{
public string RecepieName { get; set; }
//public int MentorID { get; set; }
public string Ingredient { get; set; }
public int CookingTime { get; set; }
public string Level { get; set; }
public int ServingPerson { get; set; }
public string RecepieAbstration { get; set; }
public string RecepieText { get; set; }
public string Tags { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
Action Post :
//Post api/recepie
[HttpPost]
public ActionResult <RecepieReadDto> CreateRecepie(RecepieCreateDto recepieCreateDto)
{
var recepieModel = _mapper.Map<Recepie>(recepieCreateDto);
_repository.CreateRecepieObject(recepieModel);
_repository.SaveChange();
var recepieReadDto = _mapper.Map<RecepieReadDto>(recepieModel);
return CreatedAtRoute(nameof(GetRecepieByID), new { Id = recepieReadDto.ID }, recepieReadDto);
// return Ok(recepieModel);
}
you can implement solution like below code ;
1 : Create View model For input Api;
public class RecepieCreateViewModel
{
public string RecepieName { get; set; }
public List<Ingredient> Ingredient { get; set; }
public int CookingTime { get; set; }
public string Level { get; set; }
public int ServingPerson { get; set; }
public string RecepieAbstration { get; set; }
public string RecepieText { get; set; }
public string NutritionalInformation { get; set; }
public string Tags { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
public class Ingredient
{
public string ingredientName { get; set; }
public string value { get; set; }
public string measure { get; set; }
}
2 : Create Dto Model
public class RecepieCreateDto
{
public string RecepieName { get; set; }
public string Ingredient { get; set; }
public int CookingTime { get; set; }
public string Level { get; set; }
public int ServingPerson { get; set; }
public string RecepieAbstration { get; set; }
public string RecepieText { get; set; }
public string NutritionalInformation { get; set; }
public string Tags { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
3 : Cast Ingredient Model ToJson Object In Api And Create New RecepieCreateDto Like Below Code
var result=Newtonsoft.Json.JsonConvert.SerializeObject(recepieCreateDto.Ingredient);
RecepieCreateDto readDto = new RecepieCreateDto
{
CookingTime = recepieCreateDto.CookingTime,
Level = recepieCreateDto.Level ,
ModifiedDate = recepieCreateDto.ModifiedDate ,
NutritionalInformation = recepieCreateDto.NutritionalInformation ,
RecepieAbstration = recepieCreateDto.RecepieAbstration ,
RecepieName = recepieCreateDto.RecepieName ,
RecepieText = recepieCreateDto.RecepieText ,
ServingPerson = recepieCreateDto.ServingPerson ,
CreateDate = recepieCreateDto.CreateDate ,
Tags = recepieCreateDto.Tags ,
Ingredient=result,
};
in RecepieCreateDto class Ingredient is a string but in your request json Ingredient is a array.
so change RecepieCreateDto class or request json.
"[{\"ingredientName\": \"43243\", \"value\": \"33\", \"measure\": \"\" },{ \"ingredientName\": \"565\" , \"value\": \"3\", \"measure\": \"\" }]"
OR
public IList<Ingredient> Ingredient { get; set; }
You need to create a class for Ingredient property.
public class Ingredient {
public string IngredientName { get; set; }
public string Value { get; set; } // This might be an int, you can change this on your purpose.
public string Measure { get; set; } // This might be an int, you can change this on your purpose.
}
Looks like the ingredient you posting is a collection type so making Ingredient List<> or any other collection type might do it.
public class RecepieCreateDto
{
public string RecepieName { get; set; }
//public int MentorID { get; set; }
public List<Ingredient> Ingredient { get; set; }
public int CookingTime { get; set; }
public string Level { get; set; }
public int ServingPerson { get; set; }
public string RecepieAbstration { get; set; }
public string RecepieText { get; set; }
public string Tags { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
You might need to make similar changes to your Recepie model after these changes.
You are passing array for Ingredient but expecting string. Please change Ingredient to be List<Ingredient> where Ingredient is your new object which has name, value and messure. For example:
public class Ingredient
{
[Key]
int Id {get; set; }
string IngredientName { get; set; }
string Value { get; set; }
string Measure { get; set; }
}
UPDATE: please update the DTO model respectively and use it in RecepieCreateDto
public class IngredientDTO
{
string IngredientName { get; set; }
string Value { get; set; }
string Measure { get; set; }
}
I am new to both .NET Core home somebody can guide me through this.
I need to make a request to this url and save the data into database:
url:
https://covid19.mathdro.id/api
JSON output looks like this:
{"confirmed":{"value":303001,"detail":"https://covid19.mathdro.id/api/confirmed"},"recovered":{"value":91669,"detail":"https://covid19.mathdro.id/api/recovered"},"deaths":{"value":12762,"detail":"https://covid19.mathdro.id/api/deaths"},"dailySummary":"https://covid19.mathdro.id/api/daily","dailyTimeSeries":{"pattern":"https://covid19.mathdro.id/api/daily/[dateString]","example":"https://covid19.mathdro.id/api/daily/2-14-2020"},"image":"https://covid19.mathdro.id/api/og","source":"https://github.com/mathdroid/covid19","countries":"https://covid19.mathdro.id/api/countries","countryDetail":{"pattern":"https://covid19.mathdro.id/api/countries/[country]","example":"https://covid19.mathdro.id/api/countries/USA"},"lastUpdate":"2020-03-21T20:13:21.000Z"}
Model: Totals
public class Total
{
[Key]
public int Id { get; set; }
[Column(TypeName = "int")]
[Required]
public string Confirmed { get; set; }
[Column(TypeName = "int")]
[Required]
public string Recovered { get; set; }
[Column(TypeName = "int")]
[Required]
public string Deaths { get; set; }
[Column(TypeName = "datetime2")]
[Required]
public string LastUpdated { get; set; }
}
My import model:
client.BaseAddress = new Uri("https://covid19.mathdro.id/api");
var response = await client.GetAsync($"");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
I am stuck from here and cant continue.
How do I fetch the data, I need only: confirmed, recovered, deaths and lastUpdate
Pls. anybody help here...
You need to cast JSON to a Class Object. You may get your data like this by using NewtonSoft.Json
using (var client = new HttpClient())
{
string url = string.Format("https://covid19.mathdro.id/api");
var response = client.GetAsync(url).Result;
string responseAsString = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<CovidResult>(responseAsString);
}
public class CovidResult
{
[JsonProperty("confirmed")]
public ValueModel Confirmed { get; set; }
[JsonProperty("recovered")]
public ValueModel Recovered { get; set; }
[JsonProperty("deaths")]
public ValueModel Deaths { get; set; }
}
public class ValueModel
{
[JsonProperty("value")]
public int Value { get; set; }
}
You may fork or download this repo:
https://github.com/fatihyildizhan/CoronaParser
Your modal should be
public class Total
{
public Confirmed confirmed { get; set; }
public Recovered recovered { get; set; }
public Deaths deaths { get; set; }
public string dailySummary { get; set; }
public DailyTimeSeries dailyTimeSeries { get; set; }
public string image { get; set; }
public string source { get; set; }
public string countries { get; set; }
public CountryDetail countryDetail { get; set; }
public DateTime lastUpdate { get; set; }
}
public class Confirmed
{
public int value { get; set; }
public string detail { get; set; }
}
public class Recovered
{
public int value { get; set; }
public string detail { get; set; }
}
public class Deaths
{
public int value { get; set; }
public string detail { get; set; }
}
public class DailyTimeSeries
{
public string pattern { get; set; }
public string example { get; set; }
}
public class CountryDetail
{
public string pattern { get; set; }
public string example { get; set; }
}
If stringResult has an actual value all you have to do is:
JsonConvert.DeserializeObject<Total>(stringResult);
Also when in doubt about the modal you can always use http://json2csharp.com/
I suggest you to use JSon.NET aka Newtonsoft. You can add it from nuget package manager.
Here is the code to map incoming json data to your custom class Total. just add your class contructor which will take json data as argument which is typeof string, and I added one method to make code shorter
public class Total {
public Total(string json) {
JObject jObject = JObject.Parse(json);
Confirmed = GetStringFromJToken(jObject, "confirmed");
Recovered = GetStringFromJToken(jObject, "recovered");
Deaths = GetStringFromJToken(jObject, "deaths");
LastUpdated = (string)jObject["lastUpdate"];
}
private string GetStringFromJToken(JObject jObject, string key) {
JToken keyToken = jObject[key];
return (string)keyToken["value"];
}
[Key]
public int Id { get; set; }
[Column(TypeName = "int")]
[Required]
public string Confirmed { get; set; }
[Column(TypeName = "int")]
[Required]
public string Recovered { get; set; }
[Column(TypeName = "int")]
[Required]
public string Deaths { get; set; }
[Column(TypeName = "datetime2")]
[Required]
public string LastUpdated { get; set; }
}
I m using RedisClientManager and I m gettin An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll error while trying to set an object
client.Set<ApplicationUser>(user.Id, user);
And User :
public class ApplicationUser : IdentityUser
{
public string Name { get; set; }
public string Surname { get; set; }
public DateTime? BirthDay { get; set; }
public int BirthPlace { get; set; }
public int TeamId { get; set; }
public int AvatarId { get; set; }
public string Address { get; set; }
public DateTime RegisterationDate { get; set; }
public DateTime CodeSendDate { get; set; }
public string ActivationCode { get; set; }
public string PasswordResetToken { get; set; }
public string FacebookAvatar { get; set; }
public string FacebookId { get; set; }
public bool UseFacebookAvatar { get; set; }
public string IpAddress { get; set; }
public virtual Avatar Avatar { get; set; }
public ApplicationUser()
{
this.Coupons = new HashSet<Coupon>();
}
[JsonIgnore]
public virtual ICollection<Coupon> Coupons { get; set; }
}
The error occure while serialize ApplicationUser, i try to add [JsonIgnore] on ICollection beacuse of nested loop,(Coupon contains user )
I can not find whats the problem ?
I found the solution it works for me.
ApplicationUser object has Coupon and Coupon has ApplicationUser (many to many)
so the serialize going infinite loop.
I add [IgnoreDataMember]
public class ApplicationUser : IdentityUser
{
public string Name { get; set; }
public string Surname { get; set; }
public DateTime? BirthDay { get; set; }
public int BirthPlace { get; set; }
public int TeamId { get; set; }
public int AvatarId { get; set; }
public string Address { get; set; }
public DateTime RegisterationDate { get; set; }
public DateTime CodeSendDate { get; set; }
public string ActivationCode { get; set; }
public string PasswordResetToken { get; set; }
public string FacebookAvatar { get; set; }
public string FacebookId { get; set; }
public bool UseFacebookAvatar { get; set; }
public string IpAddress { get; set; }
public virtual Avatar Avatar { get; set; }
public ApplicationUser()
{
this.Coupons = new HashSet<Coupon>();
}
[IgnoreDataMember]
public virtual ICollection<Coupon> Coupons { get; set; }
}
Now i can ignore Coupon property so Servis.Stack redisClientManager can seriazlie the object.
While I am trying to call the
`var obj = JsonConvert.DeserializeObject<UserModel>({myjsonString})`
it keeps throwing me unable to deserialize exception.
To check if my json string was well formed i decided to
Parse the string and called
JsonSchema schema = JsonSchema.Parse({myjsonString});
now i get the error below, not quite sure what it means
Additional information: Expected object while parsing schema object,
got String. Path ''
**UPDATE**
"{\"Id\":5,\"Username\":\"Sid\",\"FirstName\":\"Sid \",\"LastName\":\"LastSid\",\"Email\":\"test#gmail.com\",\"Password\":\"sample\",\"GravatarHash\":\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50\",\"Country\":\"Moon\",\"OrganizationId\":1,\"IsLocked\":false,\"CreatedDate\":\"12/13/2013 2:34:28 AM\",\"UpdatedDate\":\"12/13/2013 2:34:28 AM\",\"DataLoaded\":true}"
UPDATE 2
"\"{\\\"Id\\\":5,\\\"Username\\\":\\\"Sid\\\",\\\"FirstName\\\":\\\"Siddharth \\\",\\\"LastName\\\":\\\"Kosta\\\",\\\"Email\\\":\\\"Skosta#gmail.com\\\",\\\"Password\\\":\\\"PAssword\\\",\\\"GravatarHash\\\":\\\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8c4bcd5adc1?d=retro&?s=50\\\",\\\"Country\\\":\\\"India\\\",\\\"OrganizationId\\\":1,\\\"IsLocked\\\":false,\\\"CreatedDate\\\":\\\"2013-12-13T02:34:28.037\\\",\\\"UpdatedDate\\\":\\\"2013-12-13T02:34:28.23\\\",\\\"DataLoaded\\\":true}\""
The User Model
public class UserModel
{
public Int32 Id { get; set; }
public String Username { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public String GravatarHash { get; set; }
public String Country { get; set; }
public Int32 OrganizationId { get; set; }
public Boolean IsLocked { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime UpdatedDate { get; set; }
}
I also tried
public String CreatedDate { get; set; }
public String UpdatedDate { get; set; }
thinking if the dates were causing a problem
Update:
It works perfectly fine with your UserModel, at least for me.
Assume you have such UserModel:
public class UserModel
{
public int Id { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string GravatarHash { get; set; }
public string Country { get; set; }
public int OrganizationId { get; set; }
public bool IsLocked { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime UpdatedDate { get; set; }
public bool DataLoaded { get; set; }
}
var input =
"{\"Id\":5,\"Username\":\"Sid\",\"FirstName\":\"Sid \",\"LastName\":\"LastSid\",\"Email\":\"test#gmail.com\",\"Password\":\"sample\",\"GravatarHash\":\"http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50\",\"Country\":\"Moon\",\"OrganizationId\":1,\"IsLocked\":false,\"CreatedDate\":\"12/13/2013 2:34:28 AM\",\"UpdatedDate\":\"12/13/2013 2:34:28 AM\",\"DataLoaded\":true}";
var userModel = JsonConvert.DeserializeObject<UserModel>(input);
I think the problem with your model, can you please provided it?
It looks to me like your JSON is getting double serialized. (Having a bunch of extra backslashes in your JSON is a symptom of this.) I notice in the comments on another answer that you said you are using Web API. The Web API framework takes care of serialization for you, so you do not need to call JsonConvert.SerializeObject() in those methods. Instead just return your result directly. Then you should be able to deserialize it normally in your client. See this question.
Is there a reason why you have the curly braces in
var obj = JsonConvert.DeserializeObject<UserModel>({myjsonString})
That seems like the source of the error. Change it to:
var obj = JsonConvert.DeserializeObject<UserModel>(myjsonString)
You're missing the DataLoaded property.
public bool DataLoaded { get; set; }
In future, use this website to generate your C# classes from JSON.
http://json2csharp.com/
EDIT:
Try this step by step...
Copy and paste this class exactly as is.
public class UserModel
{
public int Id { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string GravatarHash { get; set; }
public string Country { get; set; }
public int OrganizationId { get; set; }
public bool IsLocked { get; set; }
public string CreatedDate { get; set; }
public string UpdatedDate { get; set; }
public bool DataLoaded { get; set; }
}
Now in the console have this:
var jsonString = #"{""Id"":5,""Username"":""Sid"",""FirstName"":""Sid "",""LastName"":""LastSid"",""Email"":""test#gmail.com"",""Password"":""sample"",""GravatarHash"":""http://www.gravatar.com/avatar/f4f901415af5aff35801e8444cd5adc1?d=retro&?s=50"",""Country"":""Moon"",""OrganizationId"":1,""IsLocked"":false,""CreatedDate"":""12/13/2013 2:34:28 AM"",""UpdatedDate"":""12/13/2013 2:34:28 AM"",""DataLoaded"":true}";
var user = JsonConvert.DeserializeObject<UserModel>(jsonString);
Console.WriteLine(user.Country);
Console.ReadLine();