Created
January 12, 2024 10:26
-
-
Save irfanbaysal/5b2551e4b7c4a119b0dd756b799a9688 to your computer and use it in GitHub Desktop.
Json Examples Part 2
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 Newtonsoft.Json.Linq; | |
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 Start() | |
{ | |
Debug.Log($"Unformatted :{serializedVehicle}"); | |
BeautifyJson(); | |
Debug.Log($"Formatted : {serializedVehicle}"); | |
} | |
private void Serialize() | |
{ | |
serializedVehicle = JsonConvert.SerializeObject(vehicles); | |
} | |
private void Deserialize() | |
{ | |
deserializedVehicles = JsonConvert.DeserializeObject<List<Vehicle>>(serializedVehicle); | |
} | |
public void BeautifyJson() | |
{ | |
JsonSerializerSettings settings = new JsonSerializerSettings() | |
{ | |
Formatting = Formatting.Indented | |
}; | |
settings.Formatting = Formatting.Indented; | |
JToken jToken = JsonConvert.DeserializeObject<JToken>(serializedVehicle, settings); | |
serializedVehicle = JsonConvert.SerializeObject(jToken, settings); | |
} | |
#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