1

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?

Paul Knopf
  • 9,568
  • 23
  • 77
  • 142

3 Answers3

2

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
  • 9,419
  • 1
  • 24
  • 38
  • It still spit out wrong information. "{\u000d\u000a \"Content\": \"\\r\\n
    \\r\\n
    – Paul Knopf Jun 19 '10 at 04:32
  • 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 Jun 19 '10 at 04:50
  • 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 Jun 19 '10 at 05:47
  • I suspect that is because wcf is trying to serialize the string. – Paul Knopf Jun 19 '10 at 06:02
0

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...

zobidafly
  • 275
  • 2
  • 9
0

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
  • 59,815
  • 13
  • 117
  • 134
  • 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 Jun 19 '10 at 06:35