parse JSON object to custom class object in action script 3 - json

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!

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

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];

There is Adobe's JSON parser.
https://github.com/mikechambers/as3corelib/tree/master/
import com.adobe.serialization.json

Related

Exclude a data member from JSon serialization

This is with the Docusign Rest api. When I call ToJson() on an EnvelopeDefinition, it returns the correct info, but I would like it to not serialize the base64 array for when I am writing this out to a log file. I tried using the [JsonIgnore] directive, but that stopped the array from being serialized altogether. Do I need to override the Serialize method on this class or just create another method, something like ToJsonForLogging() and not serialize that array?
I have created an extension method that will work for you. You can call this extension method in your code as follows
string json = envelopeDefinition.ToJsonLog(logDocumentBase64:false)
I am copying the DocumentBase64 into a temporary List and then using .ToJson() function to log without the documentBase64 property.
public static class EnvelopeDefinitionExtensions
{
public static string ToJsonLog(this EnvelopeDefinition envDefinition, bool logDocumentBase64 = true)
{
if (logDocumentBase64) return envDefinition.ToJson();
var tempDocumentBase64List = new List<string>();
foreach(var doc in envDefinition.Documents)
{
tempDocumentBase64List.Add(doc.DocumentBase64);
doc.DocumentBase64 = null;
}
string json = envDefinition.ToJson();
int i =0;
foreach(var doc in envDefinition.Documents)
{
doc.DocumentBase64 = tempDocumentBase64List[i];
i++;
}
return json;
}
}

Swift: Convert JSON String to Array of Custom Object with ObjectMapper

I am currently using the ObjectMapper for Swift (see: https://github.com/Hearst-DD/ObjectMapper/) to convert a String from a HTTP Request to an object of a custom class. The JSON I get from the request is a JSON Array, and I would like to convert this to an Array from type CustomObject.
I have tried it like this:
var object = Mapper<Array<CustomObject>>().map(string: json)
But then I get an error: Can not find member 'map'.
How should this be done?
Edit: this is my CustomObject Class, from now called ProductVariant:
public class ProductVariant: Mappable {
/* Attributes */
public var id = 0
// var size : Size = nil
public var SKU = ""
public var stock = 0
public var numberOfDefects = 0
/* Constructors */
public init?() {
// Empty Constructor
}
required public init?(_ map: Map) {
mapping(map)
}
/* Methods */
public func mapping(map: Map) {
id <- map["id"]
SKU <- map["SKU"]
stock <- map["stock"]
numberOfDefects <- map["numberOfDefects"]
}
}
I have found a solution, which seems to be working:
var list: Array<ProductVariant> = Mapper<ProductVariant>().mapArray(string: json)
When I loop through the array, it gives me the correct attributes for the CustomObject.
My mistake was that I tried to put the Array in the type of the Mapper, as shown in my question.
Another option is
let products = Mapper<ProductVariant>().mapArray(JSONString: json)
I think you need to install the object mapper pod and import ObjectMapper in your file

How to add an extra property into a serialized JSON string using json.net?

I am using Json.net in my MVC 4 program.
I have an object item of class Item.
I did:
string j = JsonConvert.SerializeObject(item);
Now I want to add an extra property, like "feeClass" : "A" into j.
How can I use Json.net to achieve this?
You have a few options.
The easiest way, as #Manvik suggested, is simply to add another property to your class and set its value prior to serializing.
If you don't want to do that, the next easiest way is to load your object into a JObject, append the new property value, then write out the JSON from there. Here is a simple example:
class Item
{
public int ID { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
Item item = new Item { ID = 1234, Name = "FooBar" };
JObject jo = JObject.FromObject(item);
jo.Add("feeClass", "A");
string json = jo.ToString();
Console.WriteLine(json);
}
}
Here is the output of the above:
{
"ID": 1234,
"Name": "FooBar",
"feeClass": "A"
}
Another possibility is to create a custom JsonConverter for your Item class and use that during serialization. A JsonConverter allows you to have complete control over what gets written during the serialization process for a particular class. You can add properties, suppress properties, or even write out a different structure if you want. For this particular situation, I think it is probably overkill, but it is another option.
Following is the cleanest way I could implement this
dynamic obj = JsonConvert.DeserializeObject(jsonstring);
obj.NewProperty = "value";
var payload = JsonConvert.SerializeObject(obj);
You could use ExpandoObject.
Deserialize to that, add your property, and serialize back.
Pseudocode:
Expando obj = JsonConvert.Deserializeobject<Expando>(jsonstring);
obj.AddeProp = "somevalue";
string addedPropString = JsonConvert.Serializeobject(obj);
I think the most efficient way to serialize a property that doesn't exist in the type is to use a custom contract resolver. This avoids littering your class with the property you don't want, and also avoids the performance hit of the extra serialization round trip that most of the other options on this page incur.
public class SpecialItemContractResolver : DefaultContractResolver {
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) {
var list = base.CreateProperties(type, memberSerialization);
if (type.Equals(typeof(Item))) {
var feeClassProperty = CreateFeeClassProperty();
list.Add(feeClassProperty);
}
return list;
}
private JsonProperty CreateFeeClassProperty() {
return new JsonProperty {
PropertyName = "feeClass",
PropertyType = typeof(string),
DeclaringType = typeof(Item),
ValueProvider = new FeeClassValueProvider(),
AttributeProvider = null,
Readable = true,
Writable = false,
ShouldSerialize = _ => true
};
}
private class FeeClassValueProvider : IValueProvider {
public object GetValue(object target) => "A";
public void SetValue(object target, object value) { }
}
}
To use this functionality:
// This could be put in a static readonly place so it's reused
var serializerSettings = new JsonSerializerSettings {
ContractResolver = new SpecialItemContractResolver()
};
// And then to serialize:
var item = new Item();
var json = JsonConvert.Serialize(item, serializerSettings);

Serializing object using messagepack and as3

This is a vary simple question, but can't find any docs on it.
I have a simple class:
public class User
{
public var name:String;
public var age:int;
}
I would like to serialize it using this:
var user:User = new User();
user.age = 15;
user.name = "mike";
//now serialize
var bytes:ByteArray = MessagePack.encoder.write(vo);
But I get an error:
Error: MessagePack handler for type base not found
How do I let MessagePack know what the User class is, how to serialize it?
MessagePack doesn't look like being able to serialize Class, like most serializer.
I suggest you to add a toObject method to your User class :
public function toObject():Object
{
return {age:this.age, name:this.name}:
}
Then you can serialize your user :
var bytes:ByteArray = MessagePack.encoder.write(user.toObject());
You can also add a static fromObject method which takes an object and returns a new User initialized with this object.
static public function fromObject(o:Object):User
{
var u = new User();
u.age = o.age;
u.name = o.name;
return u;
}

Parsing JSON DateTime from Newtonsoft's JSON Serializer

I've serialized an object using Newtonsoft's JSON serializer, and the DateTime has come through as:
/Date(1237588418563+0000)/
When I $.evalJSON() on that, it is an object but I can't find any normal Date methods like toUTCString on it.
Any ideas what I can do with this?
Use one of the JsonConverters that come with Json.NET for working with dates to get a better format. JavaScriptDateTimeConverter will automatically give you a JavaScript date.
public class LogEntry
{
public string Details { get; set; }
public DateTime LogDate { get; set; }
}
[Test]
public void WriteJsonDates()
{
LogEntry entry = new LogEntry
{
LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
Details = "Application started."
};
string defaultJson = JsonConvert.SerializeObject(entry);
// {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
// {"Details":"Application started.","LogDate":new Date(1234656000000)}
string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}
}
Documentation: Serializing Dates in JSON with Json.NET
I came up with a different approach which might be useful to some. Basically I create my own CustomDateConverter that I call when I need it. The converter takes 2 parameters, a date format e.g. yyyy-MM-dd HH:mm:ss and a TimeZoneInfo, which allows me to convert the date from UTC to the user's time zone:
public class JSONCustomDateConverter : DateTimeConverterBase
{
private TimeZoneInfo _timeZoneInfo;
private string _dateFormat;
public JSONCustomDateConverter(string dateFormat, TimeZoneInfo timeZoneInfo)
{
_dateFormat = dateFormat;
_timeZoneInfo = timeZoneInfo;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(TimeZoneInfo.ConvertTimeFromUtc(Convert.ToDateTime(value), _timeZoneInfo).ToString(_dateFormat));
writer.Flush();
}
You can use it like this:
var jsonString = JsonConvert.SerializeObject(myObject, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Converters = new List<JsonConverter>() { new JSONCustomDateConverter("yyyy-MM-dd HH:mm:ss", loggedUser.Timezone) } });
Obviously you could remove anything related to time zone if you only want custom date formatting. Let me know it that helped!
As of Newtonsoft Json.Net version 4.5r5 you use the JsonPropertyAttribute Class class and set its ItemConverterType Property property.
Usage:
// class to be serialized
public class MyClass
{
[JsonProperty(ItemConverterType = typeof(JavaScriptDateTimeConverter))]
public DateTime? DateTime1;
public DateTime? DateTime2;
}
As I have observed this will set the DateTimeConverter for all properties in this class not just the one before which is declared.
Ran into the same problem, and found a solution based on the link from Adam:
new Date(yourDate.substr(yourDate.indexOf("(") + 1, 13) - 0));
It looks like a Unix timestamp, which javascript is easily able to convert into a date object. The - 0 is simply to make javascript treat the substr output as an integer... I guess you could Number() it as well, if you don't like the looks of - 0
The JSON object contained something like this:
var data = {"CreatedDate":"/Date(1327572000000-1000)/"});
///
var oddDateTimeZone = data.CreatedDate;
var utcDateTime = oddDateTimeZone.substr(oddDateTimeZone.indexOf("(")+1, 13);
var utcZone = oddDateTimeZone.substr(oddDateTimeZone.indexOf("-")+1, 4);
var utcDateTimeZone = new Date(Number(utcDateTime)-(Number(utcZone)));
but, still it would be better to fix the JSON object so the date function fired without using something like eval() or window[]. Maybe in jQuery. Not sure.
Don't forget that the offset could be + and not just - for the offset!
Sorry I simplify a bit #James Newton-King
string date = Newtonsoft.Json.JsonConvert.SerializeObject(DateTime.Now);
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
This works for me