Server: Fix json deserialization

parent b294cb64
using System;
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Networking;
namespace Assets.Scripts.API
{
public class Server
public class Server: MonoBehaviour
{
public static string HOST_PROD = "https://quantifly.plnech.fr";
public static string HOST = "http://localhost:8990";
public Server ()
{
}
public static List<Score> GetScores ()
public void GetScores ()
{
StartCoroutine(GetScoresAsync());
Debug.Log("Done.");
}
IEnumerator GetScoresAsync() {
UnityWebRequest www = UnityWebRequest.Get(HOST + "/scores/");
www.Send();
yield return www.Send();
if (www.isError) {
Debug.LogError("Error:" + www.error);
return null;
Debug.LogError ("Error:" + www.error);
} else {
Debug.Log ("Got response: " + www.downloadHandler.text);
ScoresRes res = ScoresRes.CreateFromJson (www.downloadHandler.text);
Debug.Log ("Got scores: " + res);
}
Debug.Log("Got response: " + www.downloadHandler.text);
ScoresRes res = JsonUtility.FromJson<ScoresRes>(www.downloadHandler.text);
//Debug.Log("Got scores: " + res.scores);
string status = "{\"status\":\"ok\"}";
string mockText = "{\"scores\":[{\"playerName\":\"John Smith\",\"team\":null,\"score\":10,\"date\":\"2016-10-23T12:42:54.810Z\",\"_id\":\"d21b623e9b394993be3224de89099194\"}," +
"{\"playerName\":\"Randy\",\"team\":\"iGEM Headquarters\",\"score\":42,\"date\":\"2016-10-23T12:45:45.774Z\",\"_id\":\"a3a66de22b30450492f8f6b1bf178123\"}" +
"]}";
ScoresRes mock = ScoresRes.CreateFromJson(status, mockText); //TODO: Why does JsonUtility fail to deserialize? /o\
Debug.Log("Mock scores: " + mock);
return res.scores;
}
[System.Serializable]
[Serializable]
public class ScoresRes {
public string status { get; set;}
public List<Score> scores { get; set;}
public string status;
public Score[] scores;
public ScoresRes() {}
public static ScoresRes CreateFromJson(string status, string scores)
public static ScoresRes CreateFromJson(string scoresJSON)
{
return new ScoresRes
{
status = status,
scores = JsonUtility.FromJson<List<Score>>(scores)
};
return JsonUtility.FromJson<ScoresRes>(scoresJSON);
}
public override string ToString()
......
......@@ -33,12 +33,5 @@ public class SimpleEnnemy : MonoBehaviour
_player.GetComponent<Player>().Battery -= 8;
_player.GetComponent<Player>().SetBlinking();
GetScores(); // TODO: Successfully get scores from API
}
void GetScores() {
Debug.Log("Getting scores...");
Server.GetScores();
Debug.Log("Got scores.");
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment