简体   繁体   English

Json 属性映射 - 使用下划线

[英]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.我正在实施第 3 方 RestFul API。请求和响应数据中的大部分 Json 属性都使用下划线字符而不是空格和全部小写格式。 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.在我的内部代码中,我不喜欢这种格式,我希望我的 model 是以下格式。

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)?有没有一种简单的方法可以让序列化器/反序列化器为我做映射(使用 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)我知道我可以使用属性JsonPropertyName来做到这一点,但这意味着将属性添加到所有属性(有很多属性),尽管这种方法确实允许我在我的代码中使用更有意义的名称(其中的一些名称Json 可能会让日后访问代码的人感到有些困惑,如果他们没有主题知识的话)

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.来自 Java,您将在其中使用某种注释(JSON-B / Jackson),您将在 C# 中使用您已经提到的JsonPropertyName执行相同的操作。

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.因此,我的建议是不要摆弄实际属性,而是引入另一个 class 和方法来将第三方的表示解析为您的表示(如果您非常需要的话),除此之外, JsonPropertyName可能确实是最好的选择。

See: How to customize property names and values with System.Text.Json for further information.请参阅: 如何使用 System.Text.Json 自定义属性名称和值以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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