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
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
| Name | Type | Description |
|---|---|---|
json | string | The JSON string to deserialize. |
Returns
T — The deserialized object of type T.
Type Parameters
| Name | Type | Description |
|---|---|---|
T | The 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
| Name | Type | Description |
|---|---|---|
obj | T | The object to serialize. |
Returns
string — A JSON string representing the object.
Type Parameters
| Name | Type | Description |
|---|---|---|
T | The type of object to serialize. |