开发者

nHibernate to Json

开发者 https://www.devze.com 2023-01-26 14:35 出处:网络
I\'m aware there are lots of qu开发者_JS百科estions around this topic but I really can\'t seen to nail down a solution so would appreciate some help.

I'm aware there are lots of qu开发者_JS百科estions around this topic but I really can't seen to nail down a solution so would appreciate some help.

I've just started with S#arp Architecture, and haven't used nHibernate much before either (and not even that experienced with MVC).

I'm trying to return JSON from an nHibernate object, it has circular references, as it is from a relational database. I used the following code when I was using Linq to SQL which worked fine (using Newtonsoft's Json.NET)

return JsonConvert.SerializeObject(posts.ToArray(), Formatting.Indented, 
    new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects, Converters = { new JavaScriptDateTimeConverter() } });

but when I try it with an nHibernate object it just gives me [{"Id":1}], but when investigating through debug posts definitely has data to it (albeit only the single item in the array, but still) When I try using return Json(posts); it just complains about circular references. Hope you can help out :-)


The way I've 'solved' this in the end is by putting everything into a data transfer object, which is almost exactly the same as the object I was trying to convert to JSON, but it has allowed me to solve circular issues and also give a little more flexibility elsewhere. I'm sure it's not the best solution, but it works and as it happens solves a bunch of other problems. I just did something like this

public object GetDTO()
{
     object data = new
     {
         pageData = new
         {
            Id = Post.Id,
            pageUrl = Post.URL,
            title = Post.PageTitle,
            description = Post.PageDescription,
            user = Post.User.Name
        }
    };
    return data;
}

Solved the problem albeit not elegantly.


I'd recommend that you take a look at AutoMapper or ValueInjector

I'd recommend AutoMapper if you are only interested in creating outgoing DTOs. Its configuration and defaults are more friendly then ValueInjector's.

0

精彩评论

暂无评论...
验证码 换一张
取 消