Question

i am creating an object like this:

var myObj:Object = new Object();
myObj["someProperty"] = {
   anotherProperty: "someValue",
   whateverProperty: "anotherValue"
}

now i want to send it to a web server (rails):

var service:HTTPService = new HTTPService();
service.url = "http://server.com/some/path/entry.json";
service.method = URLRequestMethod.POST;
service.send( myObj );

the problem is that the server receives the json like this:

{"someProperty"=>"[object Object]"}

is this a problem with HTTPService? should i use the good old loader/urlrequest and serialize myself? by the way, serializing and then passing the string doesn't work, webserver receives empty request as GET.

but i kinda want to use the httpservice class though...

Was it helpful?

Solution

You can use a SerializationFilter with your HTTPService to correctly serialize the data you pass as an object to HTTPService.send().

The way in which this works is to create a custom SerializationFilter to perform the specific action required. In your case, you want to convert the outgoing body Object to a JSON format String. To do this you should override the serializeBody method:

package
{
    import mx.rpc.http.AbstractOperation;
    import mx.rpc.http.SerializationFilter;
    import com.adobe.serialization.json.JSON;

    public class JSONSerializationFilter extends SerializationFilter
    {
        override public function serializeBody(operation:AbstractOperation, obj:Object):Object
        {
            return JSON.encode(obj);
        }
    }
}

You can assign an instance of this filter to your HTTPService before calling send():

var service:HTTPService = new HTTPService();
service.url = "http://server.com/some/path/entry.json";
service.method = URLRequestMethod.POST;
//add the serialization filter
service.serializationFilter = new JSONSerializationFilter();
service.send( myObj );

Once assigned, this filter will be invoked for all the operations this HTTPService instance performs. You can also add more override methods to your custom filter to handle the incoming response.

OTHER TIPS

I highly recommend using Mike Chamber's JSON serialization library for encoding / decoding (serializing) data in JSON.

Basically, you need to convert your object into a JSON representation. The JSONEncoder class is useful for this.

There's a useful (old but still very relevant for using HTTPService + JSON) tutorial that goes through it, but essentially you should call JSON.encode() on what your "someProperty" value is.

i.e.:

var dataString:String = JSON.encode(dataValue);
dataString = escape(dataString);
myObj["someProperty"] = dataString;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top