3

I need to pass parameters in Json format from Sitecore item. I am getting Sitecore item using GlassMapper.

public interface ISomeType
{
  //some fields
}
public interface ISomeFolder
{
    IEnumerable<ISomeType> SubItems { get; set; }
}

...

var folder = _sitecoreContext.GetItem<ISomeFolder>(dataSourceId)
var list = folder.SubItems;
var json = JsonConvert.SerializeObject(list); // <= Here I get "Exception of type 'System.StackOverflowException' was thrown."

List type is Glass.Mapper.Sc.LazyItemEnumerable<ISomeType>. It contains Castle.Proxies.ISomeTypeProxy items, I can access to them. I can access to all their fields described in the interface. But I am getting System.StackOverflowException exception when trying to serialize it.

Is it possible to serialize GlassMapper objects to Json using Newtonsoft Json.NET?

If yes then what I am doing wrong? If no, what is the best way to convert GlassMapper object to Json?

4
  • 1
    The way I do it is I create a JSon-specific item that contains a subset of the fields of the original Glass-mapped item; that's because some fields may not be serializable. Also you should use the actuall item, not the Glass Mapper Proxy one (which you may get if your Glass item is lazy-loaded). Commented May 9, 2019 at 13:39
  • 1
    I believe the StackOverflowException is thrown because (depending on how you have your models set up) it tries to serialize all the parents/children, which in turn serializes their parents/children, etc. Commented May 9, 2019 at 13:42
  • @DanSinclair I have tried to avoid parents/children serialization by handling reference loop in ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore. But with no luck. Result is the same.
    – Anton
    Commented May 9, 2019 at 13:48
  • It's not referencing a loop, it's just referencing all items in both directions from your item, which will (eventually) try to serialize every item in the entire Sitecore tree. Commented May 9, 2019 at 14:08

1 Answer 1

4

The easiest way to solve this would be to use either a custom class or a dynamic one when you serialize:

var folder = _sitecoreContext.GetItem<ISomeFolder>(dataSourceId)
var list = folder.SubItems;
var json = JsonConvert.SerializeObject(list.Select(subitem => new 
                                                   { 
                                                       subitem.Field1,
                                                       subitem.Field2,
                                                       CustomFieldName = subitem.Field3
                                                   }));
1
  • Elegant solution, and quicker than the one I use! Repped. Commented May 9, 2019 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.