Interface IJsonService
Service to serialize/restore JSON. Get it using GetService < T >
It works for 2sxc/EAV data but can be used for any data which can be serialized/deserialized. Since it's a data-operation, we keep it in this namespace, even if most other things in this namespace are 2sxc-data objects.
Important This is simple object-string conversion. It doesn't change entity objects to be serializable. For that you should use the IConvertToEavLight which returns an object that can then be serialized.
Namespace: ToSic.Sxc.Services
Assembly: ToSic.Sxc.dll
Syntax
[PublicApi]
public interface IJsonService
Remarks
Introduced in 2sxc 12.05. For previous versions of 2sxc, you can just write code to access Newtonsoft directly. For more control regarding serialization, also just work with Newtonsoft directly.
Internally it uses Newtonsoft and preserves the case of keys. In future the internal engine may change (like for .net core), but we'll ensure that the result remains consistent.
Methods
| Improve this Doc View SourceTo<T>(String)
Convert a JSON to a typed object.
Declaration
T To<T>(string json)
Parameters
Type | Name | Description |
---|---|---|
System.String | json |
Returns
Type | Description |
---|---|
T |
Type Parameters
Name | Description |
---|---|
T |
ToJson(Object)
Convert an object to JSON.
If you need to add the JSON to HTML of a page, make sure you also use Html.Raw(...)
, otherwise it will be encoded and not usable in JavaScript.
Declaration
string ToJson(object item)
Parameters
Type | Name | Description |
---|---|---|
System.Object | item | The object to serialize |
Returns
Type | Description |
---|---|
System.String |
ToJson(Object, Int32)
Convert an object to JSON - using nicer output / indentation.
If you need to add the JSON to HTML of a page, make sure you also use Html.Raw(...)
, otherwise it will be encoded and not usable in JavaScript.
Declaration
string ToJson(object item, int indentation)
Parameters
Type | Name | Description |
---|---|---|
System.Object | item | The object to serialize |
System.Int32 | indentation | How much to indent the json - we recommend 4. As of now, it will always use 4, no matter what you set (see remarks) |
Returns
Type | Description |
---|---|
System.String |
Remarks
Added in 2sxc 12.11
But as of 2sxc 12.11 we're still using an old Newtonsoft, so we cannot really control the indentation depth. If you call this, it will always indent using 4 spaces. In a future release we'll probably use a newer Newtonsoft with which we can then use the indentation as needed.
ToObject(String)
Convert a json to an anonymous object. This is a very technical thing to do, so only use it if you know why you're doing this.
It's usually better to use AsDynamic(String, String) or To<T>(String)
Declaration
object ToObject(string json)
Parameters
Type | Name | Description |
---|---|---|
System.String | json |
Returns
Type | Description |
---|---|
System.Object |