AS3 JSON.decode throwing #1009 error - actionscript-3

I am using the as3corelib JSON library and decoding some JSON from a URLLoader request. However, I'm having issues with JSON.decode throwing an error:
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
com.adobe.serialization.json::JSONTokenizer/nextChar()
at
com.adobe.serialization.json::JSONTokenizer()
at
com.adobe.serialization.json::JSONDecoder()
at
com.adobe.serialization.json::JSON$/decode()
at Main/drawMap() at
flash.events::EventDispatcher/dispatchEventFunction()
at
flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
My code is as follows:
private function storeAssets(e:Event):void
{
// returned variables from PHP call
var variables:URLVariables = new URLVariables(e.target.data);
assets = JSON.decode(variables.assets);
}
I have passed my JSON input into validators and it always returns as valid so I'm really scratching my head on this.

Your right in putting e.target.data into the URLVariables, as per this example: http://actionscriptexamples.com/2008/02/27/decoding-url-encoded-strings-in-a-flash-application-using-the-urlvariables-class-in-actionscript-30/
What I believe is happening is that URLVariables is decoding your entire string into an object, thus variables.assets is not in JSON format because it has already been converted. It could also be that variables.assets is not defined in the return data.
Trace out your variables.assets and see if it is null, or not in JSON format.
I would use eithervar variables:URLVariables = new URLVariables(e.target.data) or assets = JSON.decode(e.target.data) but not both at the same time.

Related

AS3 Dynamic access to a sound channel

I have a flash project with many soundchannels active at the same time. I want a little function to play one and loop it, and the name of the sound channel will be passed as a parameter. This is the function:
function playBGMusic(channel:String):void
{
SoundChannel(channel) = bgSound1.play();
SoundChannel(channel).addEventListener(Event.SOUND_COMPLETE, loopBGMusic);
}
playBGMusic("bgChannel1");
This doesn't works, flash gives me this error:
1105: Target of assignment must be a reference value.
I tried to simplify the function, using an static string only in the listener
function playBGMusic():void
{
bgChannel1 = bgSound1.play();
SoundChannel("bgChannel1").addEventListener(Event.SOUND_COMPLETE, loopBGMusic);
}
playBGMusic();
This time it compiles, but it gives me this error:
Error #1034: Type Coercion failed: cannot convert "bgChannel1" to
flash.media.SoundChannel.
How can I access to a sound channel from a string?
Thaks.
You need to access it in the context of this:
SoundChannel(this[channel]) or SoundChannel(this["bgChannel1"])

How to Deserialize a very Simple RestSharp JSON Object?

Forgive what surely has to be a dumb question, but I'm just starting out with C# using JSON.
I have this class:
public class DBCount
{
public string Count { get; set; }
}
I create an instance:
public DBCount dbCount;
My web service is returning this:
[{"Count":"234"}]
This code throws an invalid cast when it tries to deserialize the response:
var client = new RestClient("http://www.../")
var request = new RestRequest ("demo/jsondbcount.php",Method.GET);
request.RequestFormat = DataFormat.Json;
var response = client.Execute (request);
RestSharp.Deserializers.JsonDeserializer deserialCount = new JsonDeserializer();
dbCount = deserialCount.Deserialize<DBCount> (response);
Here's the invalid cast error:
"Cannot cast from source type to destination type"
If anyone can point me to a basic, simple example of using RestSharp to deserialize a simple object I'd be very grateful. I've searched everywhere for a basic code sample.
Thanks
You may have figured this out already but the problem is []. [{"Count":"234"}] is an array of size 1 that contains a single object with the field Count.
If you want your server to return an object that will deserialize to a DBCount then return {"Count":"234"} without the [].
If you want your code to correctly deserialize [{"Count":"234"}] then you need to indicate that it's deserializing a collection like so:
deserialCount.Deserialize<List<DBCount>>(response);

Deep cloning using write byteArray not working

I'm writing a clone function for a class of mine.
var buffer:ByteArray = new ByteArray();
buffer.writeObject(this);
buffer.position = 0;
var gameblock:* = buffer.readObject();
Now at the last line when the time comes to read the object. I get these three errors together:
TypeError: Error #1009: Cannot access a property or method of a null
object reference. TypeError: Error #1034: Type Coercion failed: cannot
convert Object#c60efe9 to model.BlockData. TypeError: Error #1034:
Type Coercion failed: cannot convert Object#c5141c1 to
flash.geom.Matrix.
The class 'this' contains a user defined class BlockData and a Point . The errors are coming on that. How do you think I should clone this class?
I do overwrite the BlockData and the point again to make sure they get returned properly
Check this answer for better copy method with using of registerClassAlias method, but remember, that you can use this method only for simple cases, for example copy of data objects like TextFormat or Value Objects, you can't copy DisplayObject and its successor.

Jackson JSON custom deserializer works bad with composite object

I have a problem with my custom JSON deserializer.
I use Jackson to map JSON to Java and back. In some cases I need to write my own mapping.
I have an object (filter), which contains a set of another object(metaInfoClass). I try to deserialize the filter with Jackson, but I implemented an own deserializer for the inner object.
The JSON looks like this:
{
"freetext":false,
"cityName":null,
"regionName":null,
"countryName":null,
"maxResults":50,
"minDate":null,
"maxDate":null,
"metaInfoClasses":
[
{
"id":31,
"name":"Energy",
"D_TYPE":"Relevance"
}
],
"sources":[],
"ids":[]
}
My deserializer just works fine, it finds all the fields etc.
The problem is, that somehow (no idea why) the deserializer gets invoked on the rest of the JSON string, so the sources token is getting processed, and so on.
This is very weird, since I don't want to deserialize the big object, but only the inner metaInfoClass.
Even more weird: the CollectionDeserializer class keeps calling my deserializer with the json string even after it is ended. So nothing really happens, but the method gets called.
Any idea?
Thanks a lot!
I was able to find a solution.
I modified the implementation (in the deserialize method) to use to following code:
JsonNode tree = parser.readValueAsTree();
Iterator<Entry<String, JsonNode>> fieldNameIt = tree.getFields();
while (fieldNameIt.hasNext()) {
Entry<String, JsonNode> entry = fieldNameIt.next();
String key = entry.getKey();
String value = entry.getValue().getTextValue();
// ... custom code here
}
So with this approach, it was parsing only the right piece of the code and it's working right now.

Using DataContractJsonSerializer

I am trying to host a WCF service that responds to incoming requests by providing a json output stream. I have the following type
[DataContract]
[KnownType(typeof(List<HubCommon>))]
[KnownType(typeof(Music))]
[KnownType(typeof(AppsAndPlugins))]
[KnownType(typeof(Notifications))]
[KnownType(typeof(Scenes))]
[KnownType(typeof(Skins))]
[KnownType(typeof(Ringtones))]
[KnownType(typeof(Alarms))]
[KnownType(typeof(Widgets))]
[KnownType(typeof(Wallpapers))]
[KnownType(typeof(Soundsets))]
public class HubCommon{}
In my *.svc.cs file I do the following
List<HubCommon> hubContent = _ldapFacade.GetResults(query);
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HubCommon));
serializer.WriteObject(stream,hubContent);
So essentially I am trying to serialize a List to Json but I get the following error on the "WriteObject" execution:-
The server encountered an error processing the request. The exception message is 'Type 'System.Collections.Generic.List`1[[HubContentCore.Domain.HubCommon, HubContentCore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name 'ArrayOfHubCommon:http://schemas.datacontract.org/2004/07/HubContentCore.Domain' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'
What am I missing here ?
Thanks in advance.
The type of your DataContractJsonSerializer is HubCommon but you are writing an object of type List<HubCommon> and HubCommon is not added to the KnownTypAttribute