I have a generic entity class.
if T is guid, I want to initialize new guid value .
if T is int, I want to initialize id =0;
if T is string I want to initialize id =string.empty
What is the most suitable way to do this ?
public class BaseEntity<T>{
public string Id { get; set; } ;
public DateTime? CreatedAt { get; set; } = DateTime.Now;
public DateTime? UpdatedAt { get; set; }= DateTime.Now;
public DateTime? DeletedAt { get; set; }
}
You may want to consider using the default keyword to create an instance of any given type at runtime. However, with your given examples, your intentions may not simply be limited to avoiding unset properties.
Given that possibility, you could dynamically create the desired type and box/unbox it to trick the compiler - such as the example I've provided below.
This isn't generally recommended becuase of it's limited scope and general un-maintainability and error-pronedness.
You have other options as well such as creating generic instances using reflection, this may not be ideal since you have very specific "default" values that using reflection may just increase the complexity of the problem more than using a switch()(depending on your target framework, or if/else(like the example i've provided below.)
public class BaseEntity<T>
{
public T Id { get; set; } = (T)GetDefault<T>();
public DateTime? CreatedAt { get; set; } = DateTime.Now;
public DateTime? UpdatedAt { get; set; } = DateTime.Now;
public DateTime? DeletedAt { get; set; }
private static object GetDefault<U>()
{
Type paramType = typeof(U);
if(paramType == typeof(string))
{
return string.Empty;
}
else if(paramType == typeof(Guid))
{
return Guid.NewGuid();
}
return default(U);
}
}
I'm trying to post an array tat one of it's members (th) is an array of strings, I stringify the array, here is hob it looks stringified:
[{"id":"201669887","name":"אורה","Sunday":"1","Monday":"1","Tuesday":"1","Wednesday":"0","Thursday":"1","Friday":"1","Sunday1":"1","Monday1":"1","Tuesday1":"1","Wednesday1":"0","Thursday1":"1","Friday1":"0","totalWorkHour":9,"th":["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""],"year":" ","schoolName":null,"schoolNumber":null},{"id":"201669887","name":"חנה","Sunday":"1","Monday":"1","Tuesday":"1","Wednesday":"0","Thursday":"1","Friday":"1","Sunday1":"1","Monday1":"1","Tuesday1":"1","Wednesday1":"0","Thursday1":"1","Friday1":"0","totalWorkHour":9,"th":["","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""]
I have a model in Mvc:
public class teachersExcelDataModel
{
.....
public int Thursday1 { get; set; }
public int Friday1 { get; set; }
public int totalWorkHour { get; set; }
public List<string> th { get; set; }
public string schoolName { get; set; }
public int schoolNumber { get; set; }
public string month { get; set; }
public string year { get; set; }
public teachersExcelDataModel()
{
th = new List<string>();
}
}
here is how i send it:
this.http.post(this.accessPointUrl3, JSON.stringify(this.sendData), { headers: this.headers }).subscribe(
noteRecord => {
if (noteRecord)
this.a = true;
}
);
and here is how I get it:
public void PostExportExcel([FromBody]List<teachersExcelDataModel>json)
but it comes null,
if i get it as object[], it;s okay,
where am i wrong?
Your example JSON string is not in correct format.
After fixing the format of the json, you will see that you are trying to parse schoolNumber field to integer, which in your case is null and I guess internally the framework throws exception.
Trying to parse the data to object[] does not require parsing null to integer, so now you know why it works in this case
the json format is incorrect based on what i can see from the question. missing "}" and "]" too.
passing a Json value like this one(this will be the var jsonValue in code):
"{\"Something\":0,\"Something2\":10,\"Something3\":{\"Something4\":17,\"Something5\":38042,\"Something6\":38043,\"Id\":215},\"Something7\":215,\"SomethingId\":42,\"Something8\":\"AString, Gläser\",\"Something8\":\"44-55-18\",\"Status\":{\"Caption\":\"Fixed\",\"Value\":7},\"Type\":\"Article\",\"Id\":97,\"#Delete\":true,\"Something9\":\"8\"}"
to the following code:
var deserializer = new JsonSerializer();
const string regex = #"/Date\((.*?)\+(.*?)\)/";
var reader = new JsonTextReader(new StringReader(jsonValue));
returnValue = deserializer.Deserialize(reader, type);
type is the typeof https://dotnetfiddle.net/LMPEl0 (thank you Craig) (sorry for the weird names, can't disclose the actual ones...)
The jsonvalue is generated by input in an editable cell of a DataTable and apparently places previously null values in the end of the json string.
I get a null value in the "Something9" property in the returnValue, instead of 8(Something9 was null before and set to 8 through an editable Cell of a DataTable)
Is there some problem with the Json value that I can't see?
Or do I need some setting in the Deserializer?
Thanks
You don't show what your type is so I generated one using http://json2csharp.com.
public class Something3
{
public int Something4 { get; set; }
public int Something5 { get; set; }
public int Something6 { get; set; }
public int Id { get; set; }
}
public class Status
{
public string Caption { get; set; }
public int Value { get; set; }
}
public class RootObject
{
public int Something { get; set; }
public int Something2 { get; set; }
public Something3 Something3 { get; set; }
public int Something7 { get; set; }
public int SomethingId { get; set; }
public string Something8 { get; set; }
public Status Status { get; set; }
public string Type { get; set; }
public int Id { get; set; }
[JsonProperty("#Delete")]
public bool Delete { get; set; }
public string Something9 { get; set; }
}
Because one of your properties has a name that is not valid as a .NET property I added the [JsonProperty] attribute to that one. After that it worked perfectly. Perhaps the problem is with how you declared the #Delete JSON property in your .NET type. Given that Something9 comes after that property it would be my guess that that's part of the problem.
Here's the fiddle.
https://dotnetfiddle.net/McZF9Q
While Craig's answer helped a lot and finally led to a solution the exact answer to the problem was the following:
The Status object is an Enum and was not Deserialized correctly.
Due to that, anything that followed in the Json string was also not deserialized.
Implementing a custom Enum Deserializer was the solution. There are other Questions in stackoverflow that helped with this, particularly this one here:
How can I ignore unknown enum values during json deserialization?
Thank you everyone :)
I receive this JSON string (part of a really big one) back from an oracle server (data is unchangeable) but now I have the tedious problem of not being able to deserialize this..
"rows":[
{
"1":"0000000001",
"2":"SPARE00002",
"5":"151.3354",
"13":"100",
"100000":"000000",
"100001":"FFFFFF",
"rowid":"0000000001"
},
with using NewtonSoft.JSon it creates the class :
public class Row
{
public string __invalid_name__1 { get; set; }
public string __invalid_name__2 { get; set; }
public string __invalid_name__5 { get; set; }
public string __invalid_name__13 { get; set; }
public string __invalid_name__100000 { get; set; }
public string __invalid_name__100001 { get; set; }
public string rowid { get; set; }
}
And while trying to deserialise into the class I get the awesome error :
Could not evaluate expression.
Is there any way to format this correctly so c# realises the string NAME is the same as the property name sent by the JSON string?
Any help is highly appreciated!
EDIT! Found the solution!
By adding [JsonProperty("1")] ..etc to the invalid name strings, the problem solved itself!
Awesome!
On each of the invalid property names, add the attribute: [JsonProperty("1")]