How to send array through HTTPservice in Adobe Flex 3 - actionscript-3

How to send array in Httpservice in Adobe Flex3

I am not quite sure what you mean by sending an array to a httpservice. If you mean to send an array to a httpservice with the same field name, you can pass an array as field value.
var service:HTTPService = new HTTPService();
service.useProxy = true;
service.destination = "myservicet";
service.resultFormat = HTTPService.RESULT_FORMAT_XML;
var fields:Array = ["categories", "organisation"];
var params:Object = new Object();
params.q = "stackoverflow";
params.rows = 0;
params.facet = "true";
params["facet.field"] = fields;
service.send(params);
The HTTPService will convert this to the url parameters:
facet=true&q=stackoverflow&facet%2Efield=categories&facet%2Efield=organisation&rows=0
Hope this helps!
Added for more clarity. When there is only 1 argument in the array, do not pass the fields as an array. For some reason, flex will not send this to the http service

It really depends what is the back end technology you're using. If you're sending it to PHP you could try:
var fields:Array = ["categories", "organisation"];
var params:Object = {};
params.q = "stackoverflow";
params.rows = 0;
params.facet = "true";
params["facet.field[]"] = fields;
service.send(params);
PHP will generate an array for you.
AFAIR this works fine in Rails as well.

if it is a simple string array, you can join it with a well know separator char, and on the other site, split the string with the same separator back to an array.

If it is a simple array, you could send it as a comma separated string.
httpService.request = new Object;
httpService.request.csv = array.toString();

Related

How to make Json.stringify ignore certain class memebers?

I'm using the latest Haxe and HaxeFlixel to make a simple game prototype.
I have the following class...
class GameData
{
public var playerHealth: Int;
public var playerScore: Int;
public var levelName: String;
public function new(playerHealth: Int = 0, playerScore: Int = 0, levelName: String = "")
{
this.playerHealth = playerHealth;
this.playerScore = playerScore;
this.levelName = levelName;
}
}
I convert it to JSON as follows...
Json.stringify(new GameData(64, 512, "Level 1"));
Is there's a way I can make it so the stringify ignores certain members?
haxe.Json has no mechanism to exclude fields, so I would recommend using a third-party library such as json2object that does. Here you can simply annotate fields that should be ignored with #:jignored:
#:jignored
public var levelName:String;
var data = new GameData(100, 10, "Level 1");
var json = new json2object.JsonWriter<GameData>().write(data);
trace(json); // {"playerHealth": 100,"playerScore": 10}
There are some possible workarounds that don't involve adding a library to your project, but they don't seem very nice:
Don't serialize the object directly, but a structure that only includes the desired fields:
var data = new GameData(100, 10, "Level 1");
var json = Json.stringify({
playerHealth: data.playerHealth,
playerScore: data.playerScore
});
trace(json); // {"playerHealth":100,"playerScore":10}
Remove the unwanted fields after serialization - this seems rather hacky as it involves a lot of unnecessary overhead due to an additional Json.parse() and Json.stringify() call:
var json = Json.stringify(new GameData(100, 10, "Level 1"));
var data:haxe.DynamicAccess<String> = Json.parse(json);
data.remove("levelName");
json = Json.stringify(data);
trace(json); // {"playerHealth":100,"playerScore":10}
Depending on your exact situation, it can be desirable to make a slightly modified version of standard library's JsonPrinter - for example, in GMEdit I allow JSON objects to have an hxOrder: Array<String> field, which, if provided, determines the field order for printing, and is initialized to a static array. You can make a similar scheme for field inclusion/exclusion.

Sending data to a JSON with AS3

I've asked my client to share his database login and password but he can't give me full access to his database (security reason I suppose).
He told me to use a REST/JSON service that allows to post the data via this url with a specific key that allows him to identify all the datas coming from my app.
Here's what I did :
var urlRequest:URLRequest = new URLRequest("the_url_using JSON service");
urlRequest.method = URLRequestMethod.POST;
var urlvars: URLVariables = new URLVariables;
urlvars.observer_name = "Test Coco";
urlvars.observation_number = "5433";
trace("urlvars = "+urlvars);
urlRequest.data = urlvars;
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, onComplete);
urlLoader.load(urlRequest);
It's working, as it's sending the data, but the data format seems to be incorrect..
the url returns this error : "Observer name is Missing"
And the "trace (urlvars)" output :
urlvars = observer%5Fname=Test%20Coco&observation%5Fnumber=5433
So I think the problem come from the special character or something like that (as you can "observer_name" results by "observer%5Fname" and we can see a lot of %5")
Any idea how can I solve this ?
JSON string is a string representation of a generic object. Basically you go:
var anObject:Object =
{
"observer_name": "Test Coco",
"observation_number": 5433
};
or you can construct it
var anObject:Object = new Object;
anObject['observer_name'] = "Test Coco";
anObject['observation_number'] = 5433;
and then you convert it to String and attach to request
var jsonString:String = JSON.stringify(anObject);
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = jsonString;
Read more about it: https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/JSON.html
Keep in mind that I don't know the specifics of that REST server of yours and the code above just might not work as it is. I only explain how to send a JSON string as a POST request.

Is is possible to pass a string object inside another object?

I have a string and i would like to pass it by reference in a object.
var str:String = '';
var object:Object = {s:str};
object.s = 'test';
trace(str); // i would like this to output test but it is just blank
trace(object.s); //this has a value stored in it
Is this possible or am i thinking about this wrong?
What i am trying to do is update the str value by updating object.s. I want the sting object to be inside the object not the value of the str.
I want it to do something more like this
var obj2:Object = new Object();
obj2.txt = '';
var object:Object = {s:obj2};
object.s.txt = 'test';
trace(obj2.txt); // outputs test
trace(object.s.txt); //outputs test
Of course it is possible. In the above example i suspect the trace works fine, but since there is no value, it does not display anything. I don't know actionscript very well, but since it compiles down to javascript then all objects are passed by reference. your example code actually has two objects in it one called string that is a string with no value assigned, and the other an object with a property called s that is a string. that it why there is no output.
var string:String = '';
var object:Object = {s:string};
object.s = 'test';
string = object.s;
trace(string); // i would like this to output test but it is just blank
trace(object.s);
This should show you what you want to see, and is passed by reference, unless actionscript enforces pass by value, which i do not believe it does

nodejs merge array

Im doint some nodejs fiddling with blogposts from wordpress and geotagging of theese posts. I have integrated geolite into nodejs and from wordpress i get the client id. Here is what my nodejs code looks like for now.
native.on('data',
function(data)
{
//console.log(data)
listener.sockets.emit('notification', data);
jsonstring = JSON.parse(data)
var ip = jsonstring.clientip
var geo = geoip.lookup(ip);
console.log(ip);
console.log(geo);
listener.sockets.emit('geodata', geo);
}
);
As you can see the lat / long is sent seperate from the json encoded data to the socket.
I want to merge the lat / long into "data" and sent is as 1 object. I cant figure out how to do this. i Hope someone can help me out with this.
An expando/ad-hoc property or two should suffice:
listener.sockets.emit('notification', data);
jsonstring = JSON.parse(data)
var ip = jsonstring.clientip
var geo = geoip.lookup(ip);
jsonstring.geo = geo;
// or
jsonstring.lat = geo.lat;
jsonstring.lng = geo.lng;
Add the geo information as another property of your parsed data object before emitting it:
native.on('data',
function(data)
{
var obj = JSON.parse(data)
obj.geo = geoip.lookup(obj.ip);
listener.sockets.emit('notification', JSON.stringify(obj));
}
);
You can also use
listener.sockets.emit('notification', data);
jsonstring = JSON.parse(data)
var ip = jsonstring.clientip
var geo = geoip.lookup(ip);
jsonstring['geo'] = geo;
to append the data in jsonstring
[ ] will be more helpful when we have dynamic key values

html5 local storage value

Say I have the following for storing in a localstorage
var storageObject = {};
storageObject.value = myvalue;
storageObject.timestamp = d.getTime();
localStorage.setItem(myref, JSON.stringify(storageObject));
How do I use the getItem to retreive the value?
Simply:
localStorage.getItem(myref);
Or even:
localStorage[myref];
https://developer.mozilla.org/en/DOM/Storage#localStorage
Edit to restore original object from JSON, simply parse it:
var revivedObject = JSON.parse( localStorage.getItem(myref) );
// console.log(revivedObject);