Reputation: 24500
I am using ASP.NET MVC 2 with Visual Studio 2010. A lot of my controller actions need to serialize my POCO domain objects into JSON. BTW I use nhibernate as my ORM.
I am using System.Web.Script.Serialization.JavaScriptSerializer. It handles simple properties well (int, string, date, etc.), but it skips reference properties, so I have to map my object to anonymous type, and then feed this anonymous type to the JavaScriptSerializer like this:
Public Class Order
Public Property ID As Integer
Public Property Customer As User
End Class
Function Details() As ActionResult
Dim realorder As Order = DB.Get(Of Order)(id)
Dim flattenedorder As New With {
.id = realorder.ID, .customerid = realorder.Customer.ID}
Dim encoder = New System.Web.Script.Serialization.JavaScriptSerializer()
ViewData("order") = encoder.Serialize(flattenedorder)
Return View()
End Function
In the above example, Order.ID is an int, but Order.Customer is a reference to another object. I have to create anonymous type where I specify .customerid = realorder.Customer.ID, so it is serialized correctly.
What I want to know is, is there an easier way? My domain objects have lots of references and I want to avoid creating anonymous type everytime I want to serialize them to JSON.
Upvotes: 0
Views: 836
Reputation: 2030
@Endy: You can use the Json.NET for serialize you model to Json. I usually do it like that:
You can get some stuffs in my post at here. Hope I can help you!
Upvotes: 1
Reputation: 1039368
Simply return the appropriate action result and don't bother manually serializing:
Function Details() As ActionResult
Dim realorder As Order = DB.Get(Of Order)(id)
Dim flattenedorder As New With {
.id = realorder.ID, .customerid = realorder.Customer.ID}
Return Json(flattenedorder, JsonRequestBehavior.AllowGet)
End Function
As far as the references are concerned the problem stems from the fact that you are returning domain objects to the view instead of using view models. Not using view models specifically tailored to a given view is one of the most fundamental mistakes I see when people use ASP.NET MVC. So start by defining POCO objects that will represent only the portion of your domain models that is needed by the given view and then you could use AutoMapper to convert between your models and view models.
Upvotes: 2