I use ASP.NET WebAPI to provide the data getting. But when I get data in Unity by www, it appears the error message “JSON must represent an object type”.
If I test directly the raw Json string , the json string is transferred to be UserTables.
Does somebody know how to solve this problem?
Raw Json String ==> UserTables successfully
string str = "{\"Id\":1,\"UserID\":\"1\",\"UserName\":\"name1\",\"LoginType\":\"facebook \",\"email\":\"a@a\",\"Coin\":12,\"GameNoryaKey\":\"K1\"}";
UserTables usertable = DoSomethingWithTheCoroutineResult(str);
ASP.NET WebAPI Controller
// GET api/values/1
public string Get(string id)
{
using (DatabaseAKStudioEntities context = new DatabaseAKStudioEntities())
{
UserTables usertable = context.UserTables.First(a => a.UserID == id);
string yourJson = Newtonsoft.Json.JsonConvert.SerializeObject(usertable);
return yourJson;
}
}
My complete Unity C# code as below:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DemoService : MonoBehaviour
{
[System.Serializable]
public class UserTables
{
public int Id { get; set; }
public string UserID { get; set; }
public string UserName { get; set; }
public string LoginType { get; set; }
public string email { get; set; }
public int Coin { get; set; }
public string GameNoryaKey { get; set; }
}
void Start()
{
string url = "http://localhost/AKAPI/api/values/1";
WWW www = new WWW(url);
//string str = "{\"Id\":1,\"UserID\":\"1\",\"UserName\":\"name1\",\"LoginType\":\"facebook \",\"email\":\"a@a\",\"Coin\":12,\"GameNoryaKey\":\"K1\"}";
//UserTables usertable = DoSomethingWithTheCoroutineResult(str);
StartCoroutine(WaitForRequest(www));
}
IEnumerator WaitForRequest(WWW www)
{
yield return www;
// check for errors
if (www.error == null)
{
string str = www.text;
UserTables usertable = DoSomethingWithTheCoroutineResult(str);
Debug.Log("WWW Result!: " + www.text);// contains all the data sent from the server
}
else
{
Debug.Log("WWW Error: " + www.error);
}
}
public UserTables DoSomethingWithTheCoroutineResult(string result)
{
try
{
DemoService.UserTables usertable = JsonUtility.FromJson<DemoService.UserTables>(result);
return usertable;
}
catch(Exception ex)
{
print(ex.Message);
}
return null;
}
// Update is called once per frame
void Update()
{
}
}