I'm using PHP and Unity to make a simple game, and when I request dates with php, but I callback this error "ArgumentException: JSON must represent an object type."
json:
[{"id":"1","user_id":"1","nome":"Conde","level":"1","hp":"100","mana":"100","stamina":"100","dano":"35","vel_atq":"35","defesa":"35","bloqueio":"35","critico":"35","dano_critico":"35"}]
C# Unity
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System;
public class PlayerS2 : MonoBehaviour
{
public string url = "http://localhost/";
[Serializable]
public class MyPlayer
{
public int user_id;
public string nome;
public int level;
public int hp;
public int mana;
public int stamina;
public int dano;
public float vel_atq;
public int defesa;
public int bloqueio;
public int critico;
public int dano_critico;
}
public IEnumerator GetDadosPlayer(string userID)
{
MyPlayer dadosPlayer = new MyPlayer();
WWWForm form = new WWWForm();
form.AddField("userID", userID);
using (UnityWebRequest www = UnityWebRequest.Post(url + "GetDadosPlayer.php", form))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
}
else
{
Debug.Log(www.downloadHandler.text);
string json = www.downloadHandler.text;
dadosPlayer = JsonUtility.FromJson<MyPlayer>(json);
Debug.Log(dadosPlayer.nome);
}
}
}
void Start(){
StartCoroutine(GetDadosPlayer("1"));
}
}
PHP
<?php
require_once("ConexaoBD.php");
$userID = isset($_POST['userID']) ? $_POST['userID'] : "1";
$query = '
SELECT
*
FROM
player
WHERE
user_id = :user_id
';
$stmt = $conn->prepare($query);
$stmt->bindValue(':user_id',$userID);
$stmt->execute();/*
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
if(!empty($result)){
echo "";
}else{
echo $result[0]->$id;
}
*/
$results;
while($result = $stmt->fetchAll(PDO::FETCH_OBJ)){
$results = $result;
}
echo json_encode($results);
?>
[and]at the beginning and end of your json. Its easy to miss in this case because there is only one object in the array so you might miss the brackets entirely when looking at it. Deserialize to an array insteadMyPlayer[] players = JsonUtility.FromJson<MyPlayer[]>(json);Alternatively use.Trim(...)to get rid of the brackets before deserializing to a single object if you know for certain only oneMyPlayerwill ever be denoted in the json. Or change the JSON if you have control over it to remove brackets