Reputation: 5064
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!
Upvotes: 1
Views: 6335
Reputation: 31
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
Upvotes: 3
Reputation: 9572
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];
Upvotes: 2
Reputation: 2238
There is Adobe's JSON parser.
https://github.com/mikechambers/as3corelib/tree/master/
import com.adobe.serialization.json
Upvotes: 2