problems reading int from bytearray - actionscript-3

This is my first question, so do not judge strictly.
I have an object that I'm getting from php server to as3(flash) client. That object is AMF encoded, so I write server response to ByteArray:
var ba:ByteArray = new ByteArray();
ba.writeUTFBytes( rawData );
and than I'm reading object from ByteArray:
ba.position = 0;
var response:Object = ba.readObject();
Part of object contains such data:
{
'money' : 900
}
And when reading object from ByteArray, I get a seven-digit number ~ 1824344 instead of 900. But when I get form server String '900' or int value equals 100 - data reads correctly.
Has someone had such a problem?

You have to read the same way you wrote. If you write something using writeUTFBytes(), you have to read it using readUTFBytes().
In this case you should use writeObject() and readObject() because you are writing pure Object but not String.

Related

Multiple JSON Objects in AS3 Socket

I've got a Socket coming back with this JSON from a camera
var string:String = socket.readUTFBytes(socket.bytesAvailable);
string = '{"rval":0,"msg_id":514}{ "msg_id": 7, "type": "video_record_complete" ,"param":"/tmp/fuse_d/DCIM/100MEDIA/YDXJ0149.mp4"}';
i.e. 2 JSON objects in the socket.
Is there any way to split them before decoding?
This is the JSON decode error I get when I try and decode them
JSONParseError: Unexpected characters left in input stream
Is there any way to split them before decoding?
Sure, just use split():
var strings:Array = string.split("}{");
However, you can probably just extract each JSON message one at a time using readtUTF() instead of readtUTFBytes() with all bytesAvailable:
while (socket.bytesAvailable) {
var json:String = socket.readUTF();
}

JSON String parsing each character as an object

I have a JSON file that contains what I believe to be a correct JSON string:
{"title": "exampleTitle", "tipTitle": "exampleTipTitle", "tip": "exampleTip"}
I'm trying to parse said file and take out the 3 values then store them in variables, however currently, it parses each individual character as a separate object, therefore:
JSONobj[1] = "
and so on. Assuming that currentLocation = the directory location of the json file.
Code
var jsonLocation = currentLocation + "json.txt";
var request = new XMLHttpRequest();
request.open("GET", jsonLocation, false);
request.send(null);
var returnValue = request.responseText;
var JSONobj = JSON.parse(JSON.stringify(returnValue));
var headerTitle = JSONobj[0];
A few clarifications, the stringify is in because it was throwing an unexpected token error. I've tried changing the file tile to .json instead but that also makes no difference. "It also gives off a XMLHttpRequest on the main thread is deprecated" but I'm not particularly sure how to solve that issue. Any help would be appreciated.
var returnValue = request.responseText;
Here returnValue is a string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
var JSONobj = JSON.parse(JSON.stringify(returnValue));
Here you convert the string of JSON to JSON. So you have a JSON string representing a string, and that string is a representation of a data structure in JSON.
"\"{\\"title\\": \\"exampleTitle\\", \\"tipTitle\\": \\"exampleTipTitle\\", \\"tip\\": \\"exampleTip\\"}"
Then you parse it and convert it back to the original string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
So you end up back where you start.
Just don't use JSON.stringify here, and you'll convert your JSON to a JavaScript object:
var javascript_object = JSON.parse(returnValue);
Then you have an object, but it doesn't have a 0 property so it doesn't make sense to access it with javascript_object[0]. The properties have names, such as javascript_object.title.
Your JSON doesn't describe an array, so indexing into it with an index like 0 doesn't make sense. Your JSON describes an object, which will have properties with the names title, tipTitle, and tip.
Additionally, you're overdoing your parsing: You just want to parse, not stringify (which is the opposite of parsing):
var JSONobj = JSON.parse(returnValue);
So:
var JSONobj = JSON.parse(returnValue);
var headerTitle = JSONobj.title;
console.log(headerTitle); // "exampleTitle"
Side note: By the time you've assigned it to the variable you've called JSONobj, it isn't JSON anymore, it's just a normal JavaScript object, so that name is a bit misleading. If you're writing source code, and you're not dealing with a string, you're not dealing with JSON anymore. :-)

Generate a JSON object form a the value of another JSON in WP8

I am working on a WP8 app. In this I need to connect to web services whose results will be some JSON. I was trying to extract some data from the result that the web service provide. I was able to extract from the initial JSON response. But I need to get some data from the value of one such key . SO I tried to generate another Json object from it. But I m stuck. please help.Please find my example code below(I am using Newtonsoft.JSon).
private void messages_buttons_Click(object sender, RoutedEventArgs e)
{
var str = "{'status': '0', 'result': '%7B%22campaign_id%22%3A%221%22%2C%22tfn%22%3A%2218773374136%22%2C%22campaign_code%22%3A%22PJC%22%2C%22ad_id%22%3A%221%22%2C%22qr_url%22%3A%22http%3A%5C%2F%5C%2F1d1.us%5C%2FPJC%5C%2F%22%2C%22campaign_name%22%3A%22PJ+Test+Campaign%22%2C%22is_active%22%3A%221%22%2C%22expire_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22start_on%22%3A%222021-05-05+00%3A00%3A00%22%2C%22alias%22%3A%22%22%2C%22icon_image_url%22%3A%22products%5C%2Fpjc%5C%2Fpjc3.jpg%22%2C%22fb_page_url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com%5C%2FJackLaLannePowerJuicerssfb%22%2C%22video_url%22%3A%22http%3A%5C%2F%5C%2Fyoutube.com%5C%2Fembed%5C%2FyZPedpRA9r0%3Fshowinfo%3D0%26autoplay%3D1%26loop%3D1%26playlist%3DyZPedpRA9r0%22%2C%22url%22%3A%22https%3A%5C%2F%5C%2Fwww.facebook.com'}";
JObject ne = JObject.Parse(str);
var x= (ne.GetValue("result")).ToString();
var z = x.Replace("%", "");
JObject newest = JObject.Parse(z);
var y = newest.GetValue("campaign_id");
MessageBox.Show(y.ToString());
}
I get an exception at "JObject newest = JObject.Parse(z);" with the message
Unexpected character encountered while parsing number: m. Path '', line 1, position 6.
Am I doing it entirely wrong?
On a general note: can I convert a value from one Json to a another JSOn Itself? i.e if the value of one json key is a string with some key value pairs, can i make a json object on that string?
You can't actually just remove the % chars to get a valid value. You need to decode the string.
If you use this:
HttpUtility.UrlDecode(x);
You'll find your "result" is actually invalid JSON:
{"campaign_id":"1","tfn":"18773374136","campaign_code":"PJC","ad_id":"1","qr_url":"http://1d1.us/PJC/","campaign_name":"PJ
Test Campaign","is_active":"1","expire_on":"2021-05-05
00:00:00","start_on":"2021-05-05
00:00:00","alias":"","icon_image_url":"products/pjc/pjc3.jpg","fb_page_url":"https://www.facebook.com/JackLaLannePowerJuicerssfb","video_url":"http://youtube.com/embed/yZPedpRA9r0?showinfo=0&autoplay=1&loop=1&playlist=yZPedpRA9r0","url":"https://www.facebook.com
So hacking the value to make it valid JSON might work for you, by adding the missing "} at the end should turn your value in to valid JSON and allow you to parse it.
JObject newest = JObject.Parse(x + "\"}");
var y = newest.GetValue("campaign_id");
It doesn't appear that z is a valid json object at this point. It is only the value of result. Try something like JObject.Parse("'result':" + z);

Couchbase - deserialize json into dynamic type

I'm trying to deserialize some JSON coming back from couchbase into a dynamic type.
The document is something like this so creating a POCO for this would be overkill:
{
UsersOnline: 1
}
I figured that something like this would do the trick, but it seems to deserialize into a dynamic object with the value just being the original JSON
var jsonObj = _client.GetJson<dynamic>(storageKey);
results in:
jsonObj { "online": 0 }
Is there anyway I can get the couchbase deserializer to generate the dynamic type for me?
Cheers
The default deserializer for the client uses .NET's binary serializer, so when you save or read a JSON string, it's just a string. GetJson will always just return a string. However, there are a couple of options:
You could convert JSON records to Dictionary instances:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
var item = client.GetJson<Dictionary<string, object>>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item["UsersOnline"], item["NewestMember"]);
Or you could use a dynamic ExpandoObject instance:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
dynamic item = client.GetJson<ExpandoObject>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item.UsersOnline, item.NewestMember);
In either case you're losing static type checking, which seems like it's OK for your purposes. In both cases you get access to the JSON properties without having to parse the JSON into a POCO though...
Edit: I wrote a couple of extension methods that may be useful and blogged about them at http://blog.couchbase.com/moving-no-schema-stack-c-and-dynamic-types

Parsing url parameters in a String

I am using the example code in flash. I want a single variable and not the whole text.
I have a dynamic textfield called OUTPUT on the stage.
var fl_TextLoader:URLLoader = new URLLoader();
var fl_TextURLRequest:URLRequest = new URLRequest("http://www.testing.com/Christmas.txt");
fl_TextLoader.addEventListener(Event.COMPLETE, fl_CompleteHandler);
function fl_CompleteHandler(event:Event):void
{
var textData:String = new String(fl_TextLoader.data);
OUTPUT.text = textData;
}
fl_TextLoader.load(fl_TextURLRequest);
The Christmas text file contents:
Var1=Jesus&Var2=Mary&Var3=Christmas
The OUTPUT comes out with the whole string. How do I get the url parameter values separately?
Like OUTPUT.text = textData.Var1; (<--- But this does not work.)
The .data property is just a string, the raw data returned by the HTTP call, so you will have to parse the variable-value pairs, either using simple .split() on the strings or using the URLVariables object, that can do the parsing for you:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLVariables.html#decode()