Skip to content

Instantly share code, notes, and snippets.

@jbtule
Created May 25, 2013 01:37
Show Gist options
  • Select an option

  • Save jbtule/5647560 to your computer and use it in GitHub Desktop.

Select an option

Save jbtule/5647560 to your computer and use it in GitHub Desktop.

Revisions

  1. jbtule created this gist May 25, 2013.
    90 changes: 90 additions & 0 deletions LosslessJson.csx
    Original 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"
    // }
    // ]
    // }
    5 changes: 5 additions & 0 deletions packages.config
    Original 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>