0

is there a way to deserialize strings to objects in actionscript:

i.e.

  var str:String = "{ id: 1, value: ['a', 500] }";

should be made into an appropriate actionscript object.

this is not json, since the keys are not wrapped in quotes.

2
  • is there a rason the strings cannot be first converted to json? this would seem like a good idea. Commented Feb 8, 2012 at 23:22
  • well actually converting should be possible. sorry i didnt think about this earlier Commented Feb 9, 2012 at 9:19

2 Answers 2

2

Ok, for that type of data pattern, there's not a nice way that I know of to do this. going off the assumption you can't affect the data to make it more JSON-like ... here's off the top of my head what I would conceptually try:

var str:String = "{ id:1, value:['a', 500] }";
// strip off the { and } characters since we've nothing nice to do that for us...
var mynewString:String = str.slice(1, str.length - 1);
var stringItems:Array = mynewString.split(",");
var obj:Object = new Object();
for (var i in stringItems)
{
    var objProps:Array = stringItems[i].split(":");
    // kill off the quotes here
    obj[props[0]] = objProps[1].slice(1, objProps[1].length - 1);

    if ( obj[props[0]].indexOf('[') == 0 ) {
        // remove [ and ] if there
        var maybeStrArray:String = obj[props[0]].slice(1, str.length - 1);

        // right now assume we're an array based on our inbound data
        var strArr:Array = maybeStrArray.split(",");
        obj[props[0]] = strArr;
    }
}   

Something like that or similar to it anyway. Yes, it's crude, and absolutely it could be fashioned in a way that is more flexible (such as move the string to array convert to its own function so I could use it elsewhere). It's just the first thing that conceptually came to mind as an answer.

Try that, tweak around with it and see if it helps.

Sign up to request clarification or add additional context in comments.

1 Comment

ill accept this answer for the effort you did. however i went with the solution to correctly format this as json and then use as3corelib.
1

You can use as3corelib library for JSON deserialization. It's really not worth spending your time on writing own implementation (except you wish so).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.