This question already has answers here:
How to apply a general rule for remapping all property names when serializing with Json.NET?
(2 answers)
Newtonsoft JsonConvert.SerializeObject ignoring JsonProperty if name is uppercase
(2 answers)
Closed 2 years ago.
I've used the built-in Visual Studio menu option "Paste Special->Paste JSON as classes" selection on a JSON string that contains dots in the names of fields. (Example: System.Title).
The generated class has the dots removed (understandably) from the property names in the class (From the above example, System.Title = SystemTitle).
Here is a snippet of an example of the JSON that I am trying to deserialize (from Microsoft TFS REST APIs):
{
"id": 27736,
"rev": 6,
"fields": {
"System.WorkItemType": "Test Case",
"System.State": "Ready",
"System.Reason": "Completed",
"System.Title": "EFCValuesTest_DenomNotPresent",
"Microsoft.VSTS.Common.StateChangeDate": "2019-02-14T21:15:37.627Z",
"Microsoft.VSTS.Common.ActivatedDate": "2019-01-25T20:25:52.743Z",
"Microsoft.VSTS.Common.Priority": 4,
},
},
Notice that although CamelCase is used, there are also dot (.) name separators as well.
When I try to deserialize the fields JSON segment into the class object, the values are not extracted. However, if I place a JsonProperty attribute with the PropertyName set to the name with dots such as [JsonProperty(PropertyName = "System.Title")], then Json.NET can resolve the name and assign the correct value upon deserialization.
Is there any way to have Json.NET do this name-lookup conversion automatically without having to assign the JsonProperty to all of the class properties that are associated with fields that have dots in the name?
Related
I have a simple value converter (ValueConverter<List<string>, string>) for a property. The code is not important, but it turns a semicolon delimited list of strings into a string array. I want to apply it to a List<string> property so that my colon-delimited database-stored column can be turned into an array of strings in .NET.
If I apply it like this, it works:
builder.Property(x => x.Pictures)
.HasColumnName("Pictures")
.HasColumnType("nvarchar(max)")
.HasConversion(new SemicolonValuesConverter());
But if I apply it like this, it doesn't:
builder.Property(x => x.Pictures)
.HasColumnName("Pictures")
.HasColumnType("nvarchar(max)")
.HasConversion<SemicolonValuesConverter>();
Class SemicolonValuesConverter is public, has a public parameterless constructor and inherits from ValueConverter<List<string>, string>. As I said, it works just fine if I pass an instance, but not if I pass the type.
The error I get is:
System.InvalidOperationException: The property 'Venue.Pictures' is of type 'List< string >' which is not supported by the current database provider. Either change the property CLR type, or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
I have a JWT with the following content:
{
"jti":"b17373d5-2755-435b-916a-9b87c9354427",
"resource_access":"{"test-app":{"roles":["anonymous"]}}"
}
the issue is the resource_access part:
it it looks like:
dictionary<string, dictionary<string, list<string>>>
The problem is that json.net gives this error:
Error converting value "{" to type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[System.String]]]'. Path 'resource_access', line 1, position 335. ---> System.ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[System.String]]].
The json validator at https://jsonformatter.curiousconcept.com/ lets this json pass as properly formatted, but I'm not sure it follows the standard to start with.
So, my question is: can this be deserialized without making a custom deserializer?
I have a JSON object of the following form.
{
"prefix.key1":"val",
"prefix.key2":"val2",
......
"anotherKey":"value",
"morekeys":"value"
}
I need all the values for the properties where the property name starts with the string "prefix". Is this possible using JsonPath?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
ASP.net MVC - Custom attribut error message with nullable properties
Can I replace default validation message for integer field? I want to localize it.
(For int: "The field Id must be a number.")
You could use the ErrorMessageResourceName property:
[Required(ErrorMessageResourceName = "SomeResource")]
[StringLength(30, ErrorMessageResourceName = "SomeOtherResource")]
public string Name { get; set; }
You may checkout this blog post for an example.
In response to this
How can I apply it for integer validation?
Firstly how are you validating integers ? Show us some code.
If your are using Regular expressions then use
[RegularExpression("pattern", ErrorMessageResourceName = "SomeResource")]
or if you are using a custom attribute, you can use this in similar fashion.
I have a .Net Web Service function that can accept one string.
That function will then serialize that string to JSON, but I only want to serialize it if it's value is not "".
I found these instructions:
http://msdn.microsoft.com/en-us/library/aa347792.aspx
[DataContract]
public class MyClass
{
[DataMember (EmitDefaultValue=false)]
public string myValue = ""
}
Unfortunatelly I can not hide the myValue from the serialization because "" is not the .Net default value for a string (how dumb is that!)
One of two option ocurred
On the web service have some kind of attribute that sets the "" to null
Have some condition on the class
I would prefer the 1st because it makes the code cleaner but an opinion would be great.
Thanks
You can explicitly set what the default value is (for the purposes of serialization) using the DefaultValueAttribute class:
[DataContract]
public class MyClass
{
[DataMember (EmitDefaultValue=false)]
[DefaultValue("")]
public string myValue = ""
}
I think you have at least a couple of options here. It's extra work but worth it.
You can encapsulate the string in a reference type. Since reference types are null if not present, that lets you know right away if a string was present or not (because the encapsulating reference type would be either non-null or null, if the string is non-empty or not.)
A final option you have is to add an extra complementary variable (perhaps a boolean) that is set on OnDeserializing/OnDeserialized/OnSerializing/OnSerialized and use this to track whether or not something was actually present on the wire. You might, for example, set this complementary variable to true only when you're actually serializing out a non-empty string and similarly