Não consigo fazer um loadData do server para o game, utilizando uma classe genérica. O json chega normalmente mas quando tento fazer o parsing da erro:
JSON:
[{"id":10,"name":"ATHLETICS","imageUrl":"","followersNumber":0}]
Error:
JSON must represent an object type: unityEngine.Debug.Log.Error(Object)
Help por favor, seguem códigos:
NODE.JS
Topic.js
var db = require('../dbconection'); //reference of dbconnection.js
var Topic = {
getMyTopicById: function(user_name, callback) {
return db.query("select id, name,imageUrl, followersNumber from topic where user_name =?", [user_name], callback);
}
};
module.exports = Topic;
Topics.js
router.post('/', function(req, res, next) {
if( req.param("tipo")=="get-my-topic")
{
var user = req.param("user_name");
Topic.getMyTopicById(user, function(err, rows) {
if (err) {
res.json(err);
} else {
console.log("CONVERTING IN JSON:" +JSON.stringify(rows));
//res.send(rows);
res.send(JSON.stringify(rows));
}
});
}//END-if( req.param("tipo")=="get-my-topic")
});
No unity
dataAPI.js:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class dataAPI : MonoBehaviour {
public string server = "http://localhost:3000/";
[Serializable]
public class Topic: Response
{
public int id;
public string name;
public string imageUrl;
public int followersNumber;
}
[Serializable]
public class Error
{
public int id;
public string message;
}
/// <summary>
/// Callback which calls after getting response from the server
/// </summary>
/// <typeparam name="T">Type of response. Each request has his own response type</typeparam>
/// <param name="success">It shows if respose is success or not</param>
/// <param name="res">Response from the server</param>
public delegate void Callback<T>(bool success, T res);
/// <summary>
/// Below there are Prizee responses which you can get from the server API
/// </summary>
[Serializable]
public class Response
{
public Error error;
}
[Serializable]
public class FollowTopicsResponse : Response
{
//public Topic[] topics;
public Topic[] topics;
}
/// <summary>
/// A routine that makes an api call to the server
/// </summary>
/// <typeparam name="T">Type of a response</typeparam>
/// <param name="action">An api method name</param>
/// <param name="data">A string array with a data where even items are keys and odd items are values. For example [key1, value1, key2, value2, ... ]</param>
/// <param name="callback">A callback with a method result</param>
IEnumerator api_call<T>(string action, string[] data, Callback<T> callback) where T : Response
{
Debug.Log ("api_call<T>:TESTING...");
//if (singleton != null)
{
Debug.Log ("api_call<T>:TESTING: [create a form for a post data]");
// create a form for a post data
WWWForm form = new WWWForm();
// create a log string
var logString = string.Format("[API_REQ {0}]", action);
// add key val if data is empty
if (data.Length == 0)
{
data = new string[] { "key", "val" };
}
// add data from an data array to the form
for (int i = 0; i < data.Length - 1; i += 2)
{
// add key and value
form.AddField(data[i], data[i + 1]);
// add log
logString += string.Format(" [{0}: {1}]", data[i], data[i + 1]);
}
Debug.Log ("api_call<T>:TESTING: [it needs to be more secure]");
// it needs to be more secure
var date = DateTime.Now.ToString();
var headers = form.headers;
headers["date"] = date;
headers["Order"] = Util.generateOrderString(data);
form.AddField("hash", Util.generateHash(data, date));
// print log string
print(logString);
Debug.Log ("api_call<T>:TESTING: [create www request www]");
Debug.Log ("api_call<T>:TESTING: [host:]" + server + action);
// create www request
//var www = new WWW(AppConfig.Instance.serverUrl + action, form.data, headers);
var www = new WWW(server + action, form.data, headers);
Debug.Log ("api_call<T>:TESTING: [wait for a response]");
// wait for a response
yield return www;
Debug.Log ("api_call<T>:TESTING: [ print log for each api call]");
// print log for each api call
print(string.Format("[API_RES {0}] [{1}]", action, www.text));
Debug.Log ("api_call<T>:TESTING: [ parse a response]");
// parse a response
parseResponse(
string.IsNullOrEmpty(www.error),
www.text,
callback
);
}
Debug.Log ("api_call<T>:TESTING FINISHED...");
}
void parseResponse<T>(bool success, string json, Callback<T> callback) where T : Response
{
Debug.Log("parseResponse<T>: [Showing json]" + json);
// if a request is not successful go to the ConnectionFailed state
Debug.Log("parseResponse<T>: [an object for a parsed response]");
// an object for a parsed response
T parsedResponse = null;
Debug.Log("parseResponse<T>: [ if json string is not empty]");
// if json string is not empty
if (json.Length > 0)
{
// try to parse
try
{
Debug.Log("parseResponse<T>: [try to parse a json string]");
// try to parse a json string
parsedResponse = JsonUtility.FromJson<T>(( json));
// if there is an error
if (parsedResponse.error.id > 0){
Debug.Log("parseResponse<T>: [if there is an error]");
callback(false, parsedResponse);
}
// if there is no error
else{
Debug.Log("parseResponse<T>: [if there is no error]");
callback(success, parsedResponse);
}
return;
}
catch (Exception e)
{
Debug.Log("parseResponse<T>: [Exception: print an error message]");
// print an error message
Debug.LogError(e.Message);
}
}
// if not parsed
callback(false, null);
}
string fixJson(string value){
value = "{\"Items\":" + value +"}";
return value;
}
public void chamada()
{
Debug.Log ("CHAMADA ->>>>>");
// call a server api method
signIn("teste", "topics", followsCallback);
Debug.Log ("CHAMADA ->>>>>SEND SERVER");
}
public void signIn(string username, string action, Callback<FollowTopicsResponse> callback)
{
_signIn(username, action, callback);
}
public void _signIn(string username, string action, Callback<FollowTopicsResponse> callback)
{
string tipo = "get-my-topic";
StartCoroutine(
api_call(
action,
new string[]
{
"user_name", username,
"tipo", tipo
},
callback
)
);
}
// a callback for a UnfollowTopics method
static void followsCallback(bool success, FollowTopicsResponse res)
{
if (success)
{
// update topics data
//topicos= res.topics;
Debug.Log ("ROTINA TOPICOS FINALIZADA:" + res.topics.Length );
}
else
{
Debug.Log ("ROTINA TOPICOS FINALIZADA: NENHUM TOPICO ENCONTRADO" );
}
}
// Use this for initialization
void Start () {
chamada ();
}
}