开发者

asp.net WCF and JSON

I know returning types in a wcv service is allowed, and it will convert the object to json. But what if I don't want to return a random type, but return a string with formatted json? I can construct json my self but it can a) be messy, and b) not auto encode html values.

How do I do build a custom formatted json string? Off the top of my had, can I return a dictionary with key, value pairs? Will the value be encoded so you can transmitted without running th开发者_运维百科e risk of malformed json?


Have a look at JSON.Net. I've used it in the past for serializing/deserializing to/from Json. It also (according to the web page) has support for converting Json to/from XML, so it seems reasonable that there would be some functions in there to build arbitrary Json strings in a way that is less error-prone than doing it yourself.


You can specify a return type of object and then use an anonymous type to return an arbitrary object. If you want to return an arbitrary collection, you can return IEnumerable, and use that to return a collection of anonymous types.


as far as I can understand, you want a webservice that returns a string that can be parsed using json (like JSON.parse(yourReturnedString)... As ckramer answered, JSON.NET can help to format your whatever dictionary into json but you should know dictionary is "json-serialised" as key:'your key', value:'your value§that can be also an object that will be serialized', so if you are using JSON.NET, you should also once it has been deserialezed, remove all the "key": and ,"value" JSON.NET returned. so good so far you should definetely declare your webmethod as a method that returns a JSON format.

hope you found a solution before this answer...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜