views:

237

answers:

2

Hi,

I need to pass (via string content of a HTTP request/response body) name value pairs of data (like a hash) back from a Ruby on Rails server to a C# client.

Anyone happen to know offhand what would be the best format to do this in? Probably XML I would guess?

tks

PS. So overall the requirement is find a C# method that convert from a String of name/value pairs in JSON format (created by Ruby/Rails) to an existing C# standard name/value pair class/variable (e.g. Array or Dictionary I guess?)

+2  A: 

Actually, JSON is supported in both, and would certainly do what you require.

Here are links to a Javascript Serializer for C#: http://stackoverflow.com/questions/401756/parsing-json-using-json-net

And as long as you require 'json' for Ruby on Rails, you can simply use the "[to_json]"[1] method.

aronchick
thanks - does this imply on the C# side there isn't a one liner that can parse JSON string to a C# variable? i.e. do you need to setup some classes etc like in the answer in the link you posted?
Greg
+2  A: 

You could to post that data as:

  • HTTP POST fields (read it with Request.Form)
  • HTTP POST field with XML (Request.Form, XmlDocument)
  • HTTP POST field with JSON data (DataContractJsonSerializer)

EDIT: I have this samples:

// Building on Silverlight to send
using (MemoryStream ms = new MemoryStream())
{
    new DataContractJsonSerializer(fileList.GetType()).WriteObject(ms, fileList);
    // send it
}

// Reading on ASHX page
JobEntry[] files = 
    new JavaScriptSerializer().Deserialize<Negocio.Cache.JobEntry[]>(
        new StreamReader(context.Request.InputStream).ReadToEnd());
Rubens Farias
thanks Rubens - I had a look at the JSON class - it seems to be more serializing to/from an object - in my case I'm going from a Rails generated string of name/value pairs in JSON form, then to be parsed by C#. Do you know how one would use these classes to effectively convert from string to a standard C# name/value pair class (Dictionary collection I guess, or just an Array?)?
Greg
You don't need to deal with parsing; create a class with same structure and consume received data directly. =)
Rubens Farias
thanks - Actually I noted the following comments on the basic Deserialize method which might be good re not having to define classes..."The Deserialize<T>() method is equivalent to first using the DeserializeObject method to obtain an object graph and then trying to cast the result to type T."This doesn't seem to be true: DeserializeObject always seems to return a Dictionary<String, Object>, which can't be cast to an arbitrary type. Convert.ChangeType doesn't work either. What type of conversion is supposed to work?
Greg
can't you work around it, sending some `<string, string>` class?
Rubens Farias
arr, this works: <BR/> var inputJson = "{\"x\":123,\"y\":\"qwerty\"}"; var jss = new JavaScriptSerializer(); var output = jss.Deserialize<Dictionary<string, string>>(inputJson);
Greg