1

I want to parse JSON string to some my custom object in Action script 3. Is there some libs to do this. Or any ideas how can I make this. Thanx!

Here is an example what I want to receive:

{
    "result":{
        "birthday_at":"0000-00-00",
        "first_name":"Myname1",
        "level":5,
        "last_name":"MySurname",
        "gender":0
    },
    "cmd":"INFO",
    "service":{
        "code":0,
        "error_desc":""
    }
}

and class UserInfo:

public class UserInfo
{
  public Date birthday_at;
  public String first_name;
  public String last_name;
  public int level;
  public int gender;
}

And I want, to parse JSON string to fields of my class? How can I do this in an easiest way and in a right way? Thanx!

3 Answers 3

3
var obj:Object = JSON.decode( jsonString );
var user:UserInfo = new UserInfo();

for ( var prop:String in obj )
    user[prop] = obj[prop];

This doesn't work for custom types with getters (read-only properties). describeType can be used to get only the properties that can be set, but there are performance issues.

Darron Schall has a brilliant solution to take your JSON.parse(jsonString) plain object and convert it to a custom typed object.

https://github.com/darronschall/ObjectTranslator

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

Comments

2

Using the class mentioned in the previous answer, you would simply need to do the following:

 var obj:Object = JSON.decode( jsonString );
 var user:UserInfo = new UserInfo();

 for ( var prop:String in obj )
    user[prop] = obj[prop];

Comments

2

There is Adobe's JSON parser.

https://github.com/mikechambers/as3corelib/tree/master/

import com.adobe.serialization.json

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.