I'm trying to convert a 2sxc App.Data to a json string.
I tried :
using System.Web.Script.Serialization;
var org = (IEnumerable<dynamic>)AsDynamic(App.Data["MyData"])
.Where(s => (s.Show == true ))
.OrderBy(n => n.Name);
string retour = new JavaScriptSerializer().Serialize(org);
but I have an error Exception has been thrown by the target of an invocation.
Any idea how to return a json string of these data?
Thank you!
There are at least three ways of doing this. Two things you must know:
Now let's look at your scenario: I assume you are in a Razor or WebApi, and want to provide the items either as hidden HTML - like a <div data='{somejson}'>
or to return it from a WebApi - for further use. I'll also assume you don't care too much about languages or related items - meaning you don't want the full data, just a basic read.
Let's look at your options:
(not recommended) the easiest for you to fully control would be to create a dictionary with the values, and serialize that
(recommended) the way EAV and 2sxc do it is to prepare data for serialization, and then let the serializer take it from there. To achieve this, there is a Serializer
-object in the EAV which you can use. You'll find it in most API calls in the source of the EAV / 2sxc - the syntax is usually something like
var Serializer = new ToSic.Eav.Serializers.Serializer();
return Serializer.Prepare(single-entity-or-Ienumerable-of-entities);
this actually does what I mentioned before - it creates a Dictionary<field-name, value-object>
which any serializer can then use. Related items are automatically converted into a list of id+title combinations, so you can work with them in JS, but without delivering the entire tree of all sub-items.
Hope this helps ;)