tags:

views:

56

answers:

2

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 the risk of malformed json?

A: 

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.

Dave Ward
http://stackoverflow.com/questions/1567173/wcf-and-anonymous-types
Paul Knopf
They aren't right about that. I'm looking at functioning code that returns an anonymous type in one of my own projects. Pasted some example code on that other question.
Dave Ward
+2  A: 

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.

ckramer
It still spit out wrong information."{\u000d\u000a \"Content\": \"\\r\\n<div>\\r\\n<input type=\\\"hidden\\\" name=\\\"__VIEWSTATE\\\" id=\\\"__VIEWSTATE\\\" value=\\\".... and etc....
Paul Knopf
I'm not really sure what to make of the output you have. Can you provide a sample of your input and what your expected/desired output should be?
ckramer
I was using the json reader/writers, using WriteProperty, WriteValue.I expected a result that didn't contain noise. The example above would of thrown errors since its not properly formatted json.
Paul Knopf
I suspect that is because wcf is trying to serialize the string.
Paul Knopf