Get and parse JSON in Actionscript - json

What I want to do is make a get request to this URL: http://api.beatport.com/catalog/3/most-popular, which should return some JSON and then parse out certain information from it.
How would I go about doing this in Actionscript 3? I'm more concerned with figuring out how to get the data to feed to a JSON parser rather than parsing the JSON, since there seem to be plenty of questions about parsing JSON. The reason I want to do this in AS3 is that I have a 3D flash visualization set up and I want to get this data, parse out the relevant bits, and then display the parsed bits in the visualization.
I'm open to any other ways of doing this that can easily be integrated with Flash besides AS3 if there's an easier way to do it in another language.

Add the corelib.swc to your library path.
Import the JSON library: import com.adobe.serialization.json.JSON;
Call your service with code something like this:
var request:URLRequest=new URLRequest();
request.url=YOUR_ENDPOINT
request.requestHeaders=[new URLRequestHeader("Content-Type", "application/json")];
request.method=URLRequestMethod.GET;
var loader:URLLoader=new URLLoader();
loader.addEventListener(Event.COMPLETE, receive);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, notAllowed);
loader.addEventListener(IOErrorEvent.IO_ERROR, notFound);
loader.load(request);
protected function receive(event:Event):void
{
var myResults:Array=JSON.decode(event.target.data);
}
Parse the results with JSON.decode(results).
as3corelib is maintained here: https://github.com/mikechambers/as3corelib#readme.

Alternatively if you're using Flash Player 11 or AIR 3.0 or higher you can use the built in JSON object to decode your JSON. It's a top level object so you dont even need to import anything, just do:
var decoded : Object = JSON.parse(loadedText);
See: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/JSON.html

I believe the as3corelib has a JSON serializer and deserializer
You can use those instead of re-inventing the wheel and writing parsing logic afresh.

Related

Persistence using Typescript

I'm currently working in a project using Electron (basically nodejs with chromium) plus Angular2
Is there any way to save a typescript object in a file?
Currently, I'm saving objects in a json file. The problem is that all object methods are lost
Should I try to save the __proto__ variable?
Should I use a framework or a special database engine?
Today I'm reading the object from a the json file and parsing it using JSON.parse. Then I reassign all the properties in a new object, which is not scalable
Any suggestion is welcome
Thanks in advance. José
I'm the OP!
I just find this library that, apparently, solve the problem
https://www.npmjs.com/package/serializer.ts
So what to do? How to have in users array of User objects instead of
plain javascript objects? Solution is to create new instances of User
object and manually copy all properties to new objects.
Alternatives? Yes, you can use this library. Purpose of this library
is to help you to map you plain javascript objects to the instances of
classes you have created.
I'll give a shot and feedback. Bests
You can export variables as json like:
myJsons.ts:
export var myVar = {
name: "John"
}
and use them inside your ts files like:
myComponent.ts:
import {myVar} from '../path-to-myJsons'
this.myJson = myVar;
this.name = this.myJson.name;

Create a new JSON file in QT5

Obviously Qt5 has better support for JSON. The Qt example http://doc.qt.io/qt-5/qtcore-json-savegame-example.html explains how to parse and also modify JSON files or object, which is great.
But for my requirement I should create a completely new JSON file, so I can't use the methods to modify existing JSON parameters. Maybe I didn't understand the examples, but how can I create a completely new JSON object?
thanks!
Should be rather straight forward:
QJsonObject myJsonObj;
myJsonObj["MyValue"] = 10;
QJsonDocument doc(myJsonObj);
QFile file("MyFile.json");
file.open(QIODevice::WriteOnly | QIODevice::Text);
file.write(doc.toJson(QJsonDocument::Indented));

How to deserialize JSON to object in Swift WITHOUT mapping

Is there a way to deserialize a JSON response to a custom object in Swift WITHOUT having to individually map each element.
Currently I am doing it manually with SwiftyJSON but it still requires me to map every field redundantly:
var myproperty1 = json["myproperty1"].stringValue
However coming from a C# background it is as simple as one line of code:
JsonConvert.DeserializeObject<CustomObject>(jsonString); //No mapping needed.
Source - http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
Since I am writing many API endpoints I would like to avoid all the boilerplate mapping code that can be prone to errors. Keep in mind that my JSON responses will be multiple levels deep with arrays of arrays. So any function would need to be recursive.
Similiar question : Automatic JSON serialization and deserialization of objects in Swift
You could use EVReflection for that. You can use code like:
var user:User = User(json:jsonString)
or
var jsonString:String = user.toJsonString()
See the GitHub page for more detailed sample code
You should be able to use key value coding for this. You'd have to make your object a subclass of NSObject for KVC to work, and then you could loop through the elements of the JSON data and use setValue:forKey to assign a value for each key in the dictionary.
Note that this would be dangerous: If the target object did not contain a value for a specific key then your code would crash, so your program would crash on JSON data that contained invalid keys. Not a good thing.

Embed a JSON file in an SWF

Can I use include in actionscript in some form?
var somevar = include "file.json";
Where "file.json" contains JSON data
It's not this simple, but possible. First, you have to embed a JSON file as is:
[Embed(source = 'file.json', mimeType='application/octet-stream')]
private static const YourJSON:Class;
Then, to get whatever is embedded (a String, a Bitmap, an SWF), you need to instantiate a variable with this type.
var somevar:String=new YourJSON();
Then you need to parse the JSON, the correct syntax for this varies by JSON and parsing library (this part is mainly determined by your Flash player target). RafH's answer has a syntax for an array and (IIRC) FP10 compatible library.
Also may want use ASC 2.0.
(from here)
New syntax allows you to use:
var h:Object = include 'conf.json'; // where conf.json contains correct JSON
No, include doesnt return a value and includes are done at compile time, so if the content of the include file change, you need to recompile the swf.
Not sure about you want to do, but it seems like loading / parsing an external JSON data file would be a better approach to look for.
Here is a good example : http://snipplr.com/view/56283/

Convert loaded string to Object

In AS3, I want lo load a file text with URLLoader. In the file text I have the following string:
{a:1,b:"string",c:["one","two"]}
Is it possible (once loaded) to convert it to an Object?
There is no intrinsic deserializer built into the language, no. But if your text file sticks to the JSON standard, then you could use a JSON parser to do the conversion for you: http://code.google.com/p/as3corelib/source/browse/#svn%2Ftrunk%2Fsrc%2Fcom%2Fadobe%2Fserialization%2Fjson
Or, if you cannot adhere to JSON, you could always write your own deserializer.
What you need is to eval the string to create the object.
This is done natively in javascript and AS2. AS3 however does not support this function.
But all is not lost. The people at Hurlant have created a library that does this "almost" as good as native JavaScript.
Here is a good example.
And another library example using d.eval
I would like to point out though that if you have accept to the source of the object string that you create a JSON object out of it. The JSON libraries are usually much easier and more reliable to use then the libraries that do Eval.
Your string is a sting with JSON format. Use JSONDecoder to decode it to an Object, like this:
var dc:JSONDecoder = new JSONDecoder("{a:1,b:'string',c:['one','two']}");
var ob:Object = dc.getValue();