jsonasp.net-mvc-2datacontractserializerdatacontracts

Share Json data between Asp.Net MVC 2 and Asp.Net server side C# code?


I created and love my Asp.Net MVC2 application. It's a very nice DDD app with Domain Model classes, View Model classes, a repository, and Json action methods to expose data.

My coworker wants to share my data with his Asp.Net Forms based C# code. He wants to pull through the Internet a class definition (like a Data Contract), then fill it with my Json results, effectively using something like a remote repository.

Any links or ideas on how to provide him with data contracts and data?

Darin Dimitrov had an excellent idea of consuming JSON data using data contracts here. Just wondering if it's possible to use MVC as the source for these items, then let him create the objects on his side, filled with data from my side.

The key to this question is how to send him my data classes, then send him my data.

class Program
{
    [DataContract]
    class Person
    {
        [DataMember(Name = "name")]
        public string Name { get; set; }
        [DataMember(Name = "surname")]
        public string Surname { get; set; }
        [DataMember(Name="age")]
        public int Age { get; set; }
    }

    static void Main(string[] args)
    {
        var json = @"{""name"" : ""michael"", ""surname"" : ""brown"", ""age"" : ""35""}";

        var serializer = new DataContractJsonSerializer(typeof(Person));
        using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            var person = (Person)serializer.ReadObject(stream);
            Console.WriteLine("Name : {0}, Surname : {1}, Age : {2}", 
                person.Name, person.Surname, person.Age);
        }
    }
}

Solution

  • Write an OData service. The format is JSON, but the tools to consume it easily -- from many languages -- are already written for you.

    The nice thing about this is that your data is now not only consumable by your JS and your friend's ASP.NET app, it's consumable by Excel, PHP, etc.