Advertisement
Guest User

JSONHelper

a guest
May 16th, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 14.66 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using Newtonsoft.Json;
  9. using Newtonsoft.Json.Linq;
  10. using UnityEngine;
  11. using UnityEngine.UI;
  12.  
  13. public class JSONHelper : MonoBehaviour
  14. {
  15.  
  16.     protected static JSONHelper instance;
  17.     public static JSONHelper Instance
  18.     {
  19.         get { return instance; }
  20.     }
  21.  
  22.  
  23.     void Awake()
  24.     {
  25.         if (instance == null)
  26.         {
  27.             instance = this;
  28.         }
  29.         else if (instance != this)
  30.         {
  31.             Destroy(gameObject);
  32.         }
  33.  
  34.         DontDestroyOnLoad(gameObject);
  35.     }
  36.  
  37.     //****************************** QUEST ******************************//
  38.     public static string ToJsonString(Quest q, bool withPicture)
  39.     {
  40.         JObject jsonQuest = new JObject(
  41.             new JProperty("_idCreator", q.IdCreator),
  42.             new JProperty("geolocalisation", JSONHelper.ToJson(q.Geolocalisation)),
  43.             new JProperty("title", q.Title),
  44.             new JProperty("description", q.Description),
  45.             new JProperty("checkpoints", JSONHelper.ToJson(q.Checkpoints, withPicture)),
  46.             new JProperty("createdAt", q.CreationDate),
  47.             new JProperty("updatedAt", q.UpdateDate),
  48.             new JProperty("statistics", JSONHelper.ToJson(q.Statistics)),
  49.             new JProperty("open", q.Open)
  50.         );
  51.         return jsonQuest.ToString();
  52.     }
  53.  
  54.  
  55.     public static JObject ToJson(Coordinates c)
  56.     {
  57.         JObject jsonCoord = new JObject(
  58.             new JProperty("x", c.x),
  59.             new JProperty("y", c.y)
  60.         );
  61.         return jsonCoord;
  62.     }
  63.  
  64.     public static JArray ToJson(List<CheckPoint> cps, bool withPicture)
  65.     {
  66.         JArray jsonCheckpoints = new JArray();
  67.         foreach (var checkPoint in cps)
  68.         {
  69.             jsonCheckpoints.Add(
  70.                 JSONHelper.ToJson(checkPoint, withPicture)
  71.             );
  72.         }
  73.  
  74.         return jsonCheckpoints;
  75.     }
  76.  
  77.     public static JObject ToJson(CheckPoint c, bool withPicture)
  78.     {
  79.         JObject jsonCheckpoint = new JObject(
  80.             new JProperty("text", c.Text),
  81.             new JProperty("question", c.Question),
  82.             new JProperty("choices", new JArray(c.Choices)),
  83.             new JProperty("enigmAnswer", c.Answer),
  84.             new JProperty("difficulty", c.Difficulty),
  85.             new JProperty("_idBadge", c.Badge)
  86.         );
  87.         if (withPicture)
  88.         {
  89.             jsonCheckpoint.Add(
  90.                 new JProperty("picture", c.Picture)    
  91.             );
  92.         }
  93.         return jsonCheckpoint;
  94.     }
  95.  
  96.     public static JArray ToJson(QuestStatistics qs)
  97.     {
  98.         JArray jsonStatistics = new JArray();
  99.         foreach (var qsu in qs.Marks)
  100.         {
  101.             jsonStatistics.Add(JSONHelper.ToJson(qsu));
  102.         }
  103.  
  104.         return jsonStatistics;
  105.     }
  106.  
  107.     public static JObject ToJson(QuestStatisticsUnit qsu)
  108.     {
  109.         JObject jsonQsu = new JObject(
  110.             new JProperty("_idUser", qsu.AssociatedUser.Id),
  111.             new JProperty("comment", qsu.Comment),
  112.             new JProperty("mark", qsu.Mark)
  113.         );
  114.         return jsonQsu;
  115.     }
  116.  
  117.     public IEnumerator ToQuest(string questJson, System.Action<Quest> b)
  118.     {
  119.         JObject parse = JObject.Parse(questJson);
  120.         string idCreator = (string) parse["_idCreator"];
  121.  
  122.         string id = (string) parse["_id"];
  123.         Coordinates geolocalisation =
  124.             new Coordinates((float) parse["geolocalisation"]["x"], (float) parse["geolocalisation"]["y"]);
  125.         string title = (string) parse["title"];
  126.         string description = (string) parse["description"];
  127.         List<CheckPoint> checkpoints = null;
  128.         yield return JSONHelper.instance.ToListCheckpoint((JArray) parse["checkpoints"], value => checkpoints = value);
  129.         //int experienceEarned = (int)parse["value"];
  130.         int experienceEarned = 0;
  131.         Quest quest = new Quest(id, geolocalisation, title, description, experienceEarned, idCreator, checkpoints);
  132.         b(quest);
  133.     }
  134.  
  135.     public IEnumerator ToQuests(string questJson, System.Action<List<Quest>> b)
  136.     {
  137.         JArray parse = JArray.Parse(questJson);
  138.         List<Quest> list = new List<Quest>();
  139.         foreach (JToken json in parse)
  140.         {
  141.             Quest q = null;
  142.             yield return ToQuest(JObject.Parse(json.ToString()).ToString(), value => q = value);
  143.             list.Add(q);
  144.         }
  145.  
  146.         b(list);
  147.     }
  148.  
  149.  
  150.     public IEnumerator ToListCheckpoint(JArray checkpointsArray, System.Action<List<CheckPoint>> b)
  151.     {
  152.         List<CheckPoint> checkpoints = new List<CheckPoint>();
  153.         foreach (var item in checkpointsArray)
  154.         {
  155.             JObject parse = JObject.Parse(item.ToString());
  156.             string text = (string) parse["text"];
  157.             string question = (string) parse["question"];
  158.             //TODO: est-ce que ça plante ici quand on ajoute les images (qui ne sont pas envoyées dans le cas de getAllQuests !)
  159.             string picture = (string) parse["picture"];
  160.             string pictureName = (string) parse["pictureName"];
  161.             JArray choicesArray = (JArray) parse["choices"];
  162.             List<string> choices = new List<string>();
  163.             foreach (var choice in choicesArray)
  164.             {
  165.                 choices.Add(choice.ToString());
  166.             }
  167.  
  168.             string answer = (string) parse["enigmAnswer"];
  169.             int difficulty = (int) parse["difficulty"];
  170.             Badge badge = null;
  171.             if ((string)parse["_idBadge"] != "" && (string)parse["_idBadge"] != null)
  172.             {
  173.                 yield return HTTPHelper.Instance.GetBadge((string)parse["_idBadge"], value => badge = value);
  174.             }
  175.             CheckPoint checkPoint = new CheckPoint(picture, pictureName, text, question, choices, answer, difficulty, badge);
  176.             checkpoints.Add(checkPoint);
  177.         }
  178.  
  179.         b(checkpoints);
  180.     }
  181.  
  182.  
  183.     //****************************** USER ******************************//
  184.  
  185.     public static string GetIDFromAuth(string auth)
  186.     {
  187.         JObject jsonAuth = JObject.Parse(auth);
  188.         return (string) jsonAuth["_id"];
  189.     }
  190.  
  191.     public static string ToJsonString(string mail, string pwd)
  192.     {
  193.         JObject jsonConnect = new JObject(
  194.             new JProperty("email", mail),
  195.             new JProperty("password", pwd)
  196.         );
  197.         return jsonConnect.ToString();
  198.     }
  199.  
  200.     public static string ToJsonString(Account a, bool creation)
  201.     {
  202.         JObject connection = new JObject(
  203.             new JProperty("email", a.Mail)
  204.         );
  205.         if (creation)
  206.         {
  207.             connection.Add("password", a.Password);
  208.         }
  209.         JObject jsonAccount = new JObject(
  210.             //new JProperty("_id", a.Id),
  211.             new JProperty("connection", connection),
  212.             new JProperty("userInformation", new JObject(
  213.                 new JProperty("lastName", a.LastName),
  214.                 new JProperty("firstName", a.FirstName),
  215.                 new JProperty("username", a.Username),
  216.                 new JProperty("accountType", a.Role.ToString())
  217.             )),
  218.             new JProperty("game", new JObject(
  219.                 new JProperty("badges", JSONHelper.ToJson(a.Badges)),
  220.                 new JProperty("quests", JSONHelper.ToJson(a.Quests)),
  221.                 new JProperty("xp", a.Xp),
  222.                 new JProperty("elapsedTime", a.ElapsedTime)
  223.             ))
  224.         );
  225.         return jsonAccount.ToString();
  226.     }
  227.  
  228.     public static string ToJsonString(User u)
  229.     {
  230.         JObject jsonAccount = new JObject(
  231.             new JProperty("userInformation", new JObject(
  232.                 new JProperty("username", u.Username)
  233.             )),
  234.             new JProperty("game", new JObject(
  235.                 new JProperty("badges", JSONHelper.ToJson(u.Badges)),
  236.                 new JProperty("quests", JSONHelper.ToJson(u.Quests)),
  237.                 new JProperty("xp", u.Xp)
  238.             ))
  239.         );
  240.         return jsonAccount.ToString();
  241.     }
  242.  
  243.     public static JArray ToJson(List<Badge> badges)
  244.     {
  245.         JArray jsonBadges = new JArray();
  246.         foreach (var badge in badges)
  247.         {
  248.             jsonBadges.Add(badge.Id);
  249.         }
  250.  
  251.         return jsonBadges;
  252.     }
  253.  
  254.     public static JArray ToJson(Dictionary<string, StateQuest> quests)
  255.     {
  256.         JArray jsonQuest = new JArray();
  257.         foreach (var quest in quests)
  258.         {
  259.             jsonQuest.Add(JSONHelper.ToJson(quest.Value));
  260.         }
  261.  
  262.         return jsonQuest;
  263.     }
  264.  
  265.     public static JObject ToJson(StateQuest quest)
  266.     {
  267.         JArray jsonCheckpoints = new JArray();
  268.         foreach (var questCheckpoint in quest.Checkpoints)
  269.         {
  270.             jsonCheckpoints.Add(JSONHelper.ToJson(questCheckpoint));
  271.         }
  272.  
  273.         JObject jsonState = new JObject(
  274.             new JProperty("_idQuest", quest.Quest.Id),
  275.             new JProperty("state", quest.Done ? "DONE" : "IN_PROGRESS"),
  276.             new JProperty("stats", new JObject(
  277.                 new JProperty("earnedXP", quest.Score),
  278.                 new JProperty("timeElapsed", quest.TimeElapsed)
  279.             )),
  280.             new JProperty("checkpoints", jsonCheckpoints)
  281.         );
  282.         return jsonState;
  283.     }
  284.  
  285.     public static JObject ToJson(StateCheckPoint checkPoint)
  286.     {
  287.         return new JObject(
  288.             new JProperty("status", checkPoint.Status.ToString()),
  289.             new JProperty("timeElapsed", checkPoint.TimeElapsed)
  290.         );
  291.     }
  292.  
  293.     public IEnumerator ToAccount(string accountJson, Action<Account> a)
  294.     {
  295.         JObject parse = JObject.Parse(accountJson);
  296.         string mail = (string) parse["connection"]["email"];
  297.         string password = (string) parse["connection"]["password"];
  298.         string firstName = (string) parse["userInformation"]["firstName"];
  299.         string lastName = (string) parse["userInformation"]["lastName"];
  300.         RoleAccount roleAccount =
  301.             (RoleAccount) Enum.Parse(typeof(RoleAccount), (string) parse["userInformation"]["accountType"]);
  302.         DateTime creationDate = (DateTime) parse["createdAt"];
  303.         DateTime updateDate = (DateTime) parse["updatedAt"];
  304.         long elapsedTime = (long) parse["game"]["elapsedTime"];
  305.         User user = new User();
  306.         yield return JSONHelper.Instance.ToUser(accountJson, value => user = value);
  307.         Account account = new Account(user, mail, password, firstName, lastName, roleAccount, creationDate, updateDate,
  308.             elapsedTime);
  309.         a(account);
  310.     }
  311.  
  312.     public IEnumerator ToUser(string userJson, Action<User> u)
  313.     {
  314.         JObject parse = JObject.Parse(userJson);
  315.         string username = (string) parse["userInformation"]["username"];
  316.         string id = (string) parse["_id"];
  317.         long xp = (long) parse["game"]["xp"];
  318.         //TODO Remplir ces champs !
  319.         List<Badge> badges = new List<Badge>();
  320.         yield return JSONHelper.Instance.ToListBadge(JObject.Parse(parse.GetValue("game").ToString()).GetValue("badges").ToString(), value => badges = value);
  321.  
  322.         Dictionary<string, StateQuest> quests = new Dictionary<string, StateQuest>();
  323.         yield return JSONHelper.Instance.ToDictState(JObject.Parse(parse.GetValue("game").ToString()).GetValue("quests").ToString(), value => quests = value);
  324.  
  325.  
  326.         User user = new User(username, id, xp, badges, quests);
  327.         u(user);
  328.     }
  329.  
  330.     public IEnumerator ToDictState(string json, Action<Dictionary<string, StateQuest>> d)
  331.     {
  332.         Dictionary<string, StateQuest> dic = new Dictionary<string, StateQuest>();
  333.  
  334.         JArray jsonQuest = JArray.Parse(json);
  335.         for (int i=0; i < jsonQuest.Count; i++)
  336.         {
  337.             JObject tokenQuest = JObject.Parse(jsonQuest[0].ToString());
  338.             StateQuest sq = null;
  339.             yield return JSONHelper.Instance.ToStateQuest(tokenQuest.ToString(), value => sq = value);
  340.             dic.Add(sq.Quest.Id, sq);
  341.         }
  342.  
  343.         d(dic);
  344.     }
  345.  
  346.     public IEnumerator ToStateQuest(string json, System.Action<StateQuest> sq)
  347.     {
  348.         JObject quest = JObject.Parse(json);
  349.         string key = (string)quest["_idQuest"];
  350.  
  351.         //TODO: Est-ce nécessaire ?
  352.  
  353.  
  354.         Quest q = null;
  355.         yield return HTTPHelper.Instance.GetQuest(key, value => q = value);
  356.  
  357.         bool done = ((string)quest["state"]) == "DONE";
  358.         double score = (double)quest["stats"]["earnedXp"];
  359.         double timeElapsed = (double)quest["stats"]["timeElapsed"];
  360.  
  361.         List<StateCheckPoint> listCheckPoints = new List<StateCheckPoint>();
  362.  
  363.         JArray checkpoints = JArray.Parse(quest.GetValue("checkpoints").ToString());
  364.         int i = 0;
  365.         foreach (var tokenCheckpoint in checkpoints)
  366.         {
  367.             JObject checkpoint = JObject.Parse(tokenCheckpoint.ToString());
  368.             StatusCheckPoint status =
  369.                 (StatusCheckPoint)Enum.Parse(typeof(StatusCheckPoint), (string)checkpoint["status"], true);
  370.             double timeCheckpoint = (double)checkpoint["timeElapsed"];
  371.  
  372.             listCheckPoints.Add(new StateCheckPoint(q.Checkpoints[i], status, timeCheckpoint));
  373.  
  374.             i++;
  375.         }
  376.  
  377.         sq(new StateQuest(q, done, score, timeElapsed, listCheckPoints));
  378.     }
  379.  
  380.     //------------------------------------------------------------------------------------------
  381.  
  382.  
  383.    
  384.     public  IEnumerator ToListBadge(string badgeArrayJson, System.Action< List<Badge> > b)
  385.     {
  386.         JArray jArray = JArray.Parse(badgeArrayJson);
  387.         List<Badge> badges = new List<Badge>();
  388.         foreach (var item in jArray)
  389.         {
  390.             string id = item.ToString();
  391.             Badge curr = null;
  392.             yield return HTTPHelper.Instance.GetBadge(id, value => curr = value);
  393.             badges.Add(curr);
  394.         }
  395.  
  396.         b(badges);
  397.     }
  398.  
  399.    
  400.  
  401.     public static Badge ToBadge(string json)
  402.     {
  403.         JObject parse = JObject.Parse(json);
  404.         string name = (string) parse["name"];
  405.         string description = (string) parse["description"];
  406.         string icon = (string) parse["picture"];
  407.         string id = (string) parse["_id"];
  408.         long xp = (long) parse["earn"];
  409.  
  410.  
  411.         Badge badge = new Badge(id, name, description, xp, icon);
  412.         return badge;
  413.     }
  414.  
  415.  
  416.     //****************************** PICTURE ******************************//
  417.  
  418.     public static string GetBase64(string img)
  419.     {
  420.         byte[] imageBytes = System.IO.File.ReadAllBytes(img);
  421.         // Convert byte[] to Base64 String
  422.         return Convert.ToBase64String(imageBytes);
  423.     }
  424.  
  425.     public static byte[] FromBase64(string img64)
  426.     {
  427.         return Convert.FromBase64String(img64);
  428.     }
  429. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement