简体   繁体   中英

Json Property Mapping - using underscore

I'm implementing a 3rd parties RestFul API. The majority of the Json properties in the request and response data is formatted with underscore characters instead of spaces and all lower case. For example

{
"message_id" : "QWERTY",
"other_reference" : 12345
}

I am not a fan of this format in my internal code, I would prefer my model to be the following.

public class data
{
string MessageId {get; set;}

int OtherReference {get; set;}
}

Is there an easy way to get the serialiser/de-serialiser to do the mapping for me (using System.Text.Json)? I know I can use the attribute JsonPropertyName to do it, but that means adding the attribute to all properties (there are a lot of them), although this method does allow me to use more meaningful names in my code (some of the names in the Json could be a little confusing to someone visiting the code at a later date if they don't have the subject knowledge)

Thanks

Coming from Java, where you'd use some sort of annotation (JSON-B / Jackson), you'd do the same in C# with the JsonPropertyName you already mentioned.

In my opinion, that's also your best option here since you cannot write a decent algorithm to insert the underscores, that would require that algorithm to somewhat understand the language used and therefore be utterly overkill, prone to errors and not even easy to develop.

My recommendation therefore would be not to fiddle around with the actual properties, rather introduce another class and method to parse the third party's representation into yours if you need it that badly, other than that, JsonPropertyName is probably really the best option.

See: How to customize property names and values with System.Text.Json for further information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM