Entity framework serialize POCO to JSON

£可爱£侵袭症+ 提交于 2019-11-28 06:46:21

问题


I'm using Ef 4.1 and I've got a POCO object I'd like to serialize to JSON, I've read there is a problem to do so when using lazy loading but I'm not sure I can because a Message can have a collection of Message.

Is there any way to do this? sirialize this kind of object into JSON?

My Message object looks like:

public class Message
{
    [Key]
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public DateTime CreatedAt { get; set; }
    public DateTime? LastModified { get; set; }

    public virtual User User { get; set; }

    public virtual Message Parent { get; set; }

    public virtual ICollection<Message> Children { get; set; }
}

回答1:


The problem is circular references. An easy way to avoid this is to use Json.Net http://james.newtonking.com/projects/json-net.aspx instead of the default MVC json serializer. The latest version of Json.Net will serialize objects with circular references out of the box. http://james.newtonking.com/projects/json/help/PreserveObjectReferences.html for more info on the problem




回答2:


Eager load it using Include(). Sample linq:

var serializeMe = (from m in MyContext.Message.Include("User") where m.Id == someValue select m).ToList();

That will tell EF to load the User navigation property right away instead of lazy loading it, and the serializer should have no problem with it then.




回答3:


How about this:

  • Mark your class as [Serializable]
  • Use the JsonSerializer to serialize your object to JSON.
  • Perhaps use eager loading on the properties in your EF query?
Message msg = new Message();
var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(msg.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, msg);
string json = Encoding.Default.GetString(ms.ToArray());


[Serializable]
public class Message
{
}



回答4:


Well, lets go by parts.

¿Why is happening this?

Because you have virtual properties. If you are using EF you actually need them if you are using Lazy loading. You can configurate your EF to not do this by this example:

        context.Configuration.ProxyCreationEnabled = false;

where context is your ObjectContext or DbContext... this assuming you are using EF. But for most scenarios this is not a good aproach.

Possible Solution

As I always say: "there are not good or bad solutions, just different ways and it depends on the context", saying that, you can create dynamic objects.

In case you only have to serialize a unique object, you can do something like this

        Json(new {@property1=yourObject.property1, @property2=yourObject.property2})

In case you have a list, well, you can do this:

        var list = new List<dynamic>();

        foreach(var item in myRepository.GetAll())
        {
            list.Add(new
            {
                @property1= item.property1,
                @property2= item.property2,
                @property3= item.property3
            });
        }
        return Json(list, JsonRequestBehavior.DenyGet);

I tried to make this as generic as I can. I hope this can help somebody!!

Best regards and have a very nice day! :)



来源:https://stackoverflow.com/questions/7235650/entity-framework-serialize-poco-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!