I'm trying to deserialize JSON data using the ServiceStack.Text
library with non-C#-like property name conventions, specifically snake case like the following:
{
"first_name": "Foo",
"last_name": "Bar"
}
I want to deserialize this into a POCO:
public class MyDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
I'm currently just doing this:
var dto = JsonSerializer.DeserializeFromString<MyDto>(dtoData);
but this won't recognize the property names. I've previously overcome this in Newtonsoft.Json
using a custom ContractResolver
. How should this be done using ServiceStack.Text
?
I'd prefer not to decorate my dto class with DataMember
attributes as this seems like a concern of the source of the data, not the dto itself, and should therefore be handled by the code performing the deserialization.
To set the name of individual properties, use the [JsonPropertyName] attribute. The property name set by this attribute: Applies in both directions, for serialization and deserialization.
JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.
ServiceStack. Text is an independent, dependency-free serialization library containing ServiceStack's core high-performance utils and text processing functionality, including: JSON, JSV and CSV Text Serializers.
Specifies the settings on a JsonSerializer object. Newtonsoft.Json.
Look at JsConfig for all the different configuration and customizations that ServiceStack's JSON and text serializers supports, e.g:
JsConfig.Init(new Config { TextCase = TextCase.SnakeCase });
Should do what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With