Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure ServiceStack.Text JsonSerializer property names when deserializing

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.

like image 271
roryf Avatar asked Feb 11 '13 12:02

roryf


People also ask

How to set JsonProperty name in c#?

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.

What is JSON property C#?

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.

What is ServiceStack text?

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.

What is Jsonserializersettings?

Specifies the settings on a JsonSerializer object. Newtonsoft.Json.


1 Answers

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.

like image 104
mythz Avatar answered Nov 09 '22 19:11

mythz