我正在使用PHP和Unity制作一个简单的游戏,当我请求与php约会时,我回调了此错误“ ArgumentException:JSON必须表示对象类型。”
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);
?>
答案 0 :(得分:2)
您正试图将一个对象数组转换为对象。
JSON周围的方括号表示一个数组。大括号代表您的对象。这行:
dadosPlayer = JsonUtility.FromJson<MyPlayer>(json);
...尝试获取JSON并将其转换为MyPlayer对象,但是JSON并不代表对象,而是代表对象数组。
使用“ fetchAll”将对象从数据库中拉出的代码旨在返回多个对象并将它们放入数组中。由于您的代码应该只从数据库中返回一个对象,而不是fetchAll,因此,请尝试查找仅从数据库中返回一个对象的函数。
它应返回的对象应如下所示:
{"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"}
不是这样的:
[{"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"}]