Created
May 25, 2013 01:37
-
-
Save jbtule/5647560 to your computer and use it in GitHub Desktop.
Revisions
-
jbtule created this gist
May 25, 2013 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,90 @@ using ImpromptuInterface; using Newtonsoft.Json.Linq; /* * This example was inspired by * "Serialization is Lossy" * http://kellabyte.com/2013/05/02/serialization-is-lossy/ */ /* helper code combining json.net and impromptu-interface note: there maybe better json.net methods for this. */ public static class LosslessJson{ public static TInterface Deserialize<TInterface>(string json) where TInterface : class { return JObject.Parse(json).ActLike<TInterface>(); } public static string Serialize(object jinterface){ return Impromptu.UndoActLike(jinterface).ToString(); } } /* Static model of data as interfaces */ public interface ICompany { int Id { get; set; } string Name { get; set; } IList<IEmployee> Employees { get; } } public interface IEmployee { int Id { get; set; } string Name { get; set; } [Alias("Work Phone")] string WorkPhone{ get; set; } } /* and action */ var origJson = @" { Id: 1, Name:'Test Inc.', Location:'Somewhere', Employees: [ { Id:1, EmployerId:39421, Name:'Joe' , 'Work Phone' : '555-0125', 'Cell Phone' : '555-2222', }, { Id:2, EmployerId:39421, Name:'Jane', 'Work Phone' : '555-3210', 'Cell Phone' : '555-4444', }, ] } "; ICompany company = LosslessJson.Deserialize<ICompany>(origJson); company.Employees[0].WorkPhone = "555-0123"; company.Employees[1].Name = "Janet"; Console.WriteLine(LosslessJson.Serialize(company)); /* Output retains data that static model was unaware of: */ // { // "Id": 1, // "Name": "Test Inc.", // "Location": "Somewhere", // "Employees": [ // { // "Id": 1, // "EmployerId": 39421, // "Name": "Joe", // "Work Phone": "555-0123", // "Cell Phone": "555-2222" // }, // { // "Id": 2, // "EmployerId": 39421, // "Name": "Janet", // "Work Phone": "555-3210", // "Cell Phone": "555-4444" // } // ] // } This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="ImpromptuInterface" version="6.2.2" targetFramework="net40" /> <package id="Newtonsoft.Json" version="5.0.5" targetFramework="net45" /> </packages>