0

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);
?>

2
  • Your JSON represents an array of MyPlayer objects as denoted by the brackets [ 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 instead MyPlayer[] 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 one MyPlayer will ever be denoted in the json. Or change the JSON if you have control over it to remove brackets Commented Oct 28, 2019 at 16:04
  • 1
    I try to do it, but cotinue error, i just change my PHP conde to it: ``` $explodeJson = explode('[',$resJson); $json = explode(']',$explodeJson[1]); echo $json[0]; ``` Now the result don't have the brackets, thanks! Commented Oct 28, 2019 at 16:24

1 Answer 1

2

You're trying to cast a one-object array as an object.

The square brackets around your JSON represents an array. The curly brackets represent your object. This line:

dadosPlayer = JsonUtility.FromJson<MyPlayer>(json);

...tries to take your JSON and turn it into a MyPlayer object, but your JSON doesn't represent an object, it represents an array of objects.

The code that is pulling your object out of the database using "fetchAll" is designed to return multiple objects and put them into an array. Since your code should only ever return one object from the database, instead of fetchAll, try to find a function that only returns one object from the database.

The object it should return should look like this:

{"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"}

not like this:

[{"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"}]
Sign up to request clarification or add additional context in comments.

4 Comments

Or JsonUtility.FromJson<MyPlayer[]>(json)[0]; (though I wouldn't recommend this unless you intend to actually read multiple player objects at once, in which case, store the result in an array first).
Thanks man, i change my PHP code. ``` $explodeJson = explode('[',$resJson); $json = explode(']',$explodeJson[1]); echo $json[0]; ``` Now the result don't have the brackets, thanks!
@Draco18s afaik you can't directly FromJson to an array .. would rather need an according wrapper class like [Serializeable] public class MyPlayers{ public MyPlayer[] Players; } and then go JsonUtility.FromJson<MyPlyers>(json).Players[0]
@derHugo One more reason why I use JSON .NET and not JsonUtility. :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.