ASP.NET Web服务对象操作
可能不是特定于 Web 服务,但是...
我有一个返回的 Web 方法:
List<Tadpole> myList = getList();
return new { data = myList , count = 5 };
它以 JSON 形式返回。
我的代码检查 myList[x].fishsticks
它实际上不是 Tadpole
类的一部分(因此会出错)。我想知道,我可以在 myList
中添加一个 fishsticks
属性来避免错误,这样当我返回数据时它就会被包含在内吗?
是否有另一种优雅的解决方案可以做到这一点?
Possibly not specific to webservices, but...
I have a webmethod that returns:
List<Tadpole> myList = getList();
return new { data = myList , count = 5 };
It returns this as JSON.
my code checks myList[x].fishsticks
which isn't actually part of the Tadpole
class (so it errors). I am wondering, can I add a fishsticks
attribute to myList
somehow to avoid the error, so it gets included when I return the data?
Is there perhaps another elegant solution for doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的示例中,您必须向
Tadpole
添加一个fishsticks
属性。另外,为什么要向 JSON 类型添加
.Count
属性?仅.data.Count
或仅返回列表并完全跳过包装器不是更有意义吗?我还没有检查
List<>
的哪些属性最近被序列化,因此它可能不包括在内,但即使是这种情况,这样做也更有意义:或者,创建一个重写 .Count 并添加序列化属性的后代类。
编辑
如果我没记错的话,匿名/动态类型在内部实现为字典,而类则不是。 (顺便说一句,匿名类型和动态对象带来了许多性能和维护问题。)
如果您出于某种原因不想修改 Tadpole,您总是可以创建一个后代类:
强类型是您的朋友,并且会节省今后您可能会遇到许多令人头疼的问题。
In your example, you'll have to add a
fishsticks
property toTadpole
.Also, why are you adding a
.Count
property to your JSON type? Wouldn't it make more sense to just.data.Count
, or just return the list and skip the wrapper entirely?I haven't checked what properties of
List<>
get serialized lately, so it's possible that it's not included, but even if that's the case it would make more sense to do this:Or, create a descendant class that overrides .Count and adds a serialization attribute.
Edit
If I remember correctly, anonymous/dynamic types are internally implemented as dictionaries, while classes are, well, not. (BTW, anonymous types and dynamic objects bring a host of performance and maintenance issues along with them.)
If you don't want to modify Tadpole for some reason, you could always create a descendant class:
Strong typing is your friend and will save you many headaches down the road.