使用 C#/Json 序列化 Web 服务中的结构

发布于 2024-10-27 11:20:42 字数 266 浏览 7 评论 0原文

我正在编写一个非常简单的 C# HttpHandler (ashx) 用作 Web 服务,并打算使用 Json.Net 跨服务器边界序列化一个小型(4-5 个字段)结构。

我有哪些选项可以在 Web 服务端序列化结构并在另一端将其反序列化为正确的类型(恰好是一个单独的 C# Web 应用程序),而无需或多或少复制和粘贴定义两端的结构?现在,该结构是 Web 服务和使用网页中的嵌套类型。我可以将它提取到自己的类程序集中,并在两端添加引用,但这似乎并不比维护两端的定义简单得多。我还有其他明智的选择吗?

I'm writing a very simple C# HttpHandler (ashx) to use as a web service, and intend to use using Json.Net to serialize a small (4-5 fields) struct across a server boundary.

What are my options for being able to serialize the struct on the web service side and deserialize it into the correct type on the other end (which happens to be a separate c# web application) without having to more or less copy and paste the definition of the struct on each end? Right now the struct is a nested type inside the webservice and in the consuming web page. I could extract it into its own class assembly, and add a reference on both ends, but that doesn't seem to be much simpler than maintaining the definition on either end. Do I have any other sensible options?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自由如风 2024-11-03 11:20:42

如果您只有几种类型要传输并且它们不太可能发生太大变化 - 只需在两端定义它即可。

如果你有很多,那么共享一个 dll

真的没有什么魔力...json设计完全没有合约。事实上,在大多数情况下,即使是匿名类型也能很好地序列化。

就我个人而言,我会使用 class 而不是 struct,不过...一如既往,更喜欢 class 除非您真的< /strong> 好主意为什么要使用 struct :大多数时候,它们的使用不正确。

If you only have a few types to transfer and they aren't likely to change much - just define it at both ends.

If you have lots, then share a dll

No magic really... json is by design quite contract free. In fact, even anonymous types serialize very nicely in most cases.

Personally I'd use a class not a struct, though... as always, prefer class unless you have a really good idea why you are using struct : most times, they are used incorrectly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文