JSONUtils.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using UnityEngine;
  3. using System.Text.RegularExpressions;
  4. using System.Collections.Generic;
  5. public class JSONUtils {
  6. /*
  7. public static Dictionary<K, V> FromJsonToDictionary<K, V>(string input) {
  8. var d = JsonUtility.FromJson<SerializableDictionary<K, V>>(input);
  9. return d.getDictionary();
  10. }
  11. publ static string FromDictionaryToJson(Dictionary<string, object> input, bool prettyPrint) {
  12. //var d = new SerializableDictionary<string, object>(input);
  13. return JsonUtility.ToJson(d, prettyPrint);
  14. }
  15. */
  16. public static Dictionary<string, object> DictionaryFromJSON(string input) {
  17. var d = new Dictionary<string, object>();
  18. //d.Add("stringKey", "value");
  19. //d.Add("numberKey", 10);
  20. //JsonUtility.FromJsonOverwrite(input, d);
  21. return d;
  22. }
  23. public static string removeComments(string input) {
  24. return Regex.Replace(input, "/\\*[\\w\\W]*?\\*/", "");
  25. }
  26. /*
  27. class SerializableDictionary<K, V>:ISerializationCallbackReceiver {
  28. // Allows a dictionary to be serialized, and deserialized into
  29. // Inspired by http://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.OnBeforeSerialize.html
  30. private Dictionary<K, V> dictionary = new Dictionary<K, V>();
  31. private List<K> keys = new List<K>();
  32. private List<V> values = new List<V>();
  33. public SerializableDictionary(Dictionary<K, V> newDictionary) {
  34. dictionary = newDictionary;
  35. }
  36. public void OnBeforeSerialize() {
  37. keys.Clear();
  38. values.Clear();
  39. foreach (var pair in dictionary) {
  40. keys.Add(pair.Key);
  41. if (pair.Value is IDictionary) {
  42. // Another dictionary
  43. values.Add(new SerializableDictionary<>(pair.value));
  44. } else {
  45. // Something else
  46. values.Add(pair.Value);
  47. }
  48. }
  49. }
  50. public void OnAfterDeserialize() {
  51. dictionary = new Dictionary<int,string>();
  52. for (int i = 0; i < < Math.Min(keys.Count, values.Count); i++) {
  53. if (values[i] is SerializableDictionary) {
  54. // Another dictionary
  55. dictionary.Add(keys[i], values[i].getDictionary());
  56. } else {
  57. // Something else
  58. dictionary.Add(keys[i], values[i]);
  59. }
  60. }
  61. }
  62. public Dictionary<K, V> getDictionary() {
  63. return dictionary;
  64. }
  65. }
  66. */
  67. }