Skip to main content

Class JsonHelper

Json helper class providing utility methods for serializing and deserializing generic objects to and from JSON, using Unity's JsonUtility. This helper wraps objects to enable serialization of generics, since Unity's built-in JSON utility does not directly support top-level generic serialization.

public class JsonHelper

Inheritance​

object→JsonHelper

Examples​

Example of serializing an object:

var myData = new MyDataType { id = 1, name = "Example" };
string json = JsonHelper.ToJson(myData);
Debug.Log(json);

Example of deserializing an object:

string json = "{\"obj\":{\"id\":1,\"name\":\"Example\"}}";
MyDataType data = JsonHelper.FromJson(json);
Debug.Log(data.name);

Methods​

FromJson<T>(string)​

Deserializes a JSON string into an object of type T. The JSON must have been generated with ToJson` to include the wrapper.

public static T FromJson<T>(string json)

Parameters​

NameTypeDescription
jsonstringThe JSON string to deserialize.

Returns​

T — The deserialized object of type T.

Type Parameters​

NameTypeDescription
TThe type of object to deserialize.

ToJson<T>(T)​

Serializes an object of type T into a JSON string. The object is wrapped to enable Unity's JsonUtility to handle generic types.

public static string ToJson<T>(T obj)

Parameters​

NameTypeDescription
objTThe object to serialize.

Returns​

string — A JSON string representing the object.

Type Parameters​

NameTypeDescription
TThe type of object to serialize.