Last active
January 12, 2024 10:26
-
-
Save irfanbaysal/4fab2f134c352d5dc286f7ed72ecaf88 to your computer and use it in GitHub Desktop.
Json Examples Part 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using Newtonsoft.Json; | |
using UnityEngine; | |
namespace JsonDeserializeExample.Scripts | |
{ | |
public enum VehicleType | |
{ | |
Default, | |
Hybrid, | |
Electric | |
} | |
public class JsonExample : MonoBehaviour | |
{ | |
[SerializeField] private List<Vehicle> vehicles = new(); | |
[SerializeField] private string serializedVehicle; | |
[SerializeField] private List<Vehicle> deserializedVehicles = new(); | |
[SerializeField] private bool serialize; | |
[SerializeField] private bool deserialize; | |
private void Serialize() | |
{ | |
serializedVehicle = JsonConvert.SerializeObject(vehicles); | |
} | |
private void Deserialize() | |
{ | |
deserializedVehicles = JsonConvert.DeserializeObject<List<Vehicle>>(serializedVehicle); | |
} | |
#if UNITY_EDITOR | |
private void OnValidate() | |
{ | |
if (serialize) | |
{ | |
Serialize(); | |
} | |
else | |
{ | |
serializedVehicle = ""; | |
} | |
if (deserialize) | |
{ | |
Deserialize(); | |
} | |
else | |
{ | |
deserializedVehicles.Clear(); | |
} | |
} | |
#endif | |
} | |
[Serializable] | |
public struct Vehicle | |
{ | |
public string id; | |
public VehicleType vehicleType; | |
public double price; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment