Handling Uknown string Value to deserialize as default Enum - json.net

I am trying to deserialize my API request body to object.
My json looks like this:
{
"EmployeeId": 123,
"EmployeeName": "Tony",
"EmployeeType": "Contractor"
}
My Class looks like:
public class RequestDto
{
public int EmployeeId {get; set;}
public string EmployeeName {get; set;}
public EmployeeType {get; set;}
}
My EmployeeType Enum
public enum EmployeeType
{
Uknown,
FullTime,
Vendor
}
I am using .net core 3.1 and i have added newtonsoft converters stringEnumConverter() in my startup.cs as well. with the above json, im getting an error converting the value to enum. I want it to be converted to default enum value when there is an unknown string value which is not available in the enum class. Is there any way .net core/newtonsoft allows me to do it without adding any custom converters which inherits from StringEnumConverter().

Related

Unable to find a default constructor to use for type Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.DynamicViewData

I am getting this error when trying to Deserialize the string from the redis cache using Newtonsoft.Json.
where HeaderTopViewComponent is model class of one of my view component ""
like: JsonConvert.DeserializeObject<HeaderTopViewComponent>(cacheValue.Result.ToString());
Unable to find a default constructor to use for type Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.DynamicViewData. Path 'ViewBag', line 1, position 340.
Output string :
{"ShowTopheaderSection":true,"PageHeader":"MSHSL","FriendlyURL":"/MSHSL","leagueList":[{"leagueId":0,"FriendlyURL":"/","leaguename":"--Select--"},{"leagueId":3,"FriendlyURL":"/MSHSL","leaguename":"MSHSL"},{"leagueId":4,"FriendlyURL":"/CHSAA","leaguename":"CHSAA"}],"HttpContext":null,"Request":null,"User":null,"RouteData":null,"ViewBag":{},"ModelState":{},"Url":null,"ViewComponentContext":{"Arguments":null,"HtmlEncoder":null,"ViewComponentDescriptor":{"DisplayName":null,"FullName":null,"Id":"9882d08a-1c50-4c59-8a30-2d9c843957e9","ShortName":null,"TypeInfo":null,"MethodInfo":null},"ViewContext":{"FormContext":null,"ClientValidationEnabled":false,"Html5DateRenderingMode":0,"ValidationSummaryMessageElement":null,"ValidationMessageElement":null,"ViewBag":{},"View":null,"ViewData":{},"TempData":null,"Writer":null,"ExecutingFilePath":null,"ActionDescriptor":null,"HttpContext":null,"ModelState":{},"RouteData":null},"ViewData":{},"Writer":null},"ViewContext":{"FormContext":null,"ClientValidationEnabled":false,"Html5DateRenderingMode":0,"ValidationSummaryMessageElement":null,"ValidationMessageElement":null,"ViewBag":{},"View":null,"ViewData":{},"TempData":null,"Writer":null,"ExecutingFilePath":null,"ActionDescriptor":null,"HttpContext":null,"ModelState":{},"RouteData":null},"ViewData":{},"ViewEngine":null}
I have fix it by adding some tag in my viewcomponent modal class and get set property like
[JsonObject(MemberSerialization.OptIn)] and [JsonProperty]
//Tag to add only selected property when Deserialize or Serialize using Newtonsoft
[JsonObject(MemberSerialization.OptIn)]
public class HeaderTopViewComponent:ViewComponent
{
#region //Property//
[JsonProperty]
public bool ShowTopheaderSection { get; set; }
[JsonProperty]
public string PageHeader { get; set; }
[JsonProperty]
public string FriendlyURL { get; set; }
[JsonProperty]
And now its working

PostUrlEncodedAsync with complex object

Hi I'm trying to post an object that is like :
public class myobj
{
public string name {get;set;}
public myEntity myentity {get;set;}
public mySecondEntity mySecondEntity {get;set;}
}
public class myEntity {get;set;}
{
public string name {get;set;}
public string description {get;set;}
}
public class mySecondEntity {get;set;}
{
public string name {get;set;}
public string description {get;set;}
}
When I use generate a new object of myObj and use PostUrlEncodedAsync it is posting it as :
name : "myname",
myentity : "detex.Models.DTO.myEntity",
mysecondentity : "detex.Models.DTO.mySecondEntity
Not sure what my namespace/class is doing in those fields. I'm posting this as
await "myurl.com".PostUrlEncodedAsync(_model).
Flurl assumes that objects passed to PostUrlEncodedAsync represent simple name/value pairs. It simply does a ToString on your values, which is why you're getting detex.Models.DTO.myEntity. Do you want those values serialized to JSON? If so you'll need to do that yourself:
"myurl.com".PostUrlEncodedAsync(new {
name = _model.name,
myentity = JsonConvert.SerializeObject(_model.myentity),
mysecondentity = JsonConvert.SerializeObject(_model.mySecondEntity)
});
Posting complex objects as URL-encoded is not typical, which is why serializing those values is not built into Flurl.

Add/insert a new entry containing complex type in Entity Framework 7 Code first

I am trying to add a new entry for my object model which has few complex type, using EF 7 code first. But it's not working and throwing exception.
Model:
public class Student
{
public int id {get; set;}
public string Name {get; set;}
public Address Address {get; set;} -> complex type
}
public class Address
{
public int Id {get;set;}
public string Location {get;set;}
}
Code first code:
class SchoolContext {
DbSet<Student> Students {get; set;}
DbSet<Address> Addresses {get; set;}
}
var context = new SchoolContext();
context.Students.Add(new Student { Id = 1, Name = "XYZ", Address = new Address { Id = 2, Location = "US" } } -> The add method has second parameter which says include dependent objects, and by default it is true.
context.SaveChanges();
This throws exception:
{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_Student_Address_AddressId\". The conflict occurred in database \"School\", table \"dbo.Address\", column 'Id'.\r\nThe statement has been terminated."}
This error I think means, the Address object does not exists in database, and if I add the address first and then Student, it works. But this is just too much code, as in my real application objects has many complex types.
Ideally this should work, but it does not.
Based on this bug report, you should add item before.
It is considered as-designed. At least until RC2.

Self referencing loops with EF5 and Newtonsoft.Json

I am using MVC4 with EF5 database first and Newtonsoft.Json for serializing objects to JSON for example in Web API controllers.
To avoid the problem of self referencing loops i set the attribute [JsonIgnore] to the specific collections in my generated classes.
My problem is now that each time i update my model i have to readd the attributes to the classes.
How can i avoid that? I think i have to edit the DBModel.tt script? What have i to do?
You should be able to use a metadata class with the MetadataType attribute. If your generated class is:
public partial class MyClass{
public string SomeProperty {get; set; }
public string SomePropertyToIgnore {get; set; }
}
Then you need to create a metadata class like so (in the same namespace):
public class MyClass_Metadata{
[JsonIgnore]
public string SomePropertyToIgnore {get; set; }
}
The create a partial of your generated class (in the same namespace) with the MetadatType attribute applied:
[MetadataType(typeof(MyClass_Metadata))]
public partial class MyClass{
}
Ref: http://msdn.microsoft.com/en-us/library/ee707339(v=vs.91).aspx

How To Pass JSON into asp.net MVC3 controller formatted like below

I've read Phil's article ( http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx ) and still can't figure out how I can take json that looks like what I have below and pass it into my controller. I don't have much control over formatting it so I need to take it like this and get the data out of it.
{
"Id":"720",
"SponsorName":"Bay Area Association of Database Developers",
"ImageURL":"~/Images/Sponsors/baadd.org.jpg",
"NavigateURL":"http://baadd.org/",
"HoverOverText":"Bay Area Association of Database Developers",
"Comment":"xx"
}
public class SponsorUpdateModel
{
public int Id {get;set;}
public string SponsorName {get;set;}
public string ImageURL {get;set;}
public string NavigateURL {get;set;}
public string HoverOverText {get;set;}
public string Comment {get;set;}
}
public ActionResult Update(SponsorUpdateModel model)
{
}

Resources