将JsonUtility与PHP json数组一起使用

时间:2017-05-24 18:51:50

标签: c# php json database unity5

我在Unity 5.5.1中使用JsonUtility和php与json时遇到了麻烦。

因为它显示出一致的错误说:

  

ArgumentException:JSON解析错误:值无效。       UnityEngine.JsonUtility.FromJson [ItemDictionary](System.String json)       (在C:/buildslave/unity/build/artifacts/generated/common/modules/JSONSerialize/JsonUtilityBindings.gen.cs:24)       DatabaseRead.LoadData(System.String val)(在Assets / Scripts / DatabaseRead.cs:40)       DatabaseRead + c__Iterator0.MoveNext()(在Assets / Scripts / DatabaseRead.cs:34)       UnityEngine.SetupCoroutine.InvokeMoveNext(IEnumerator枚举器,IntPtr returnValueAddress)       (在C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)

C#代码:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


[System.Serializable]
public class Item
{
   public string quizid;
   public string subject;
   public string question;
   public string answer;

}

[System.Serializable]
public class ItemDictionary
{
    public string[] items;
}

public class DatabaseRead : MonoBehaviour {

   public List<Item> items;

   IEnumerator Start()
   {
        WWW questionData = new WWW("localhost/game_dbase/questions.php");
        yield return questionData;

        string data = questionData.text;

        LoadData(data);

    }

    public void LoadData(string val)
    {
        ItemDictionary info = JsonUtility.FromJson<ItemDictionary>(val);

        foreach (string dictionaryitem in info.items)
        {

            LoadItem(dictionaryitem);
        }
    }


    public void LoadItem(string path)
    {
        string myLoadedItem = path;
        Item myItem = JsonUtility.FromJson<Item>(myLoadedItem);
        items.Add(myItem);
        Debug.Log(items);
    }

}

Php代码:

<?php
$servername = @"localhost";
$username =  "root";
$password = "";
$dbName = "game_dbase";

$conn = new mysqli($servername, $username, $password, $dbName);

if(!$conn){
    die("Connection Failed. ". mysqli_connect_error());
}

$sql = "SELECT quizid, subjectid, question, answer FROM quiz";
$result = mysqli_query($conn ,$sql);

$json = array();

if(mysqli_num_rows($result) > 0){

    while($row = mysqli_fetch_assoc($result)){

        $json[]=  array(
        'quizid' => $row['quizid'],
        'subjectid' => $row['subjectid'],
        'question' => $row['question'],
        'answer' => $row['answer']
        );

    }

    $jsonstring = json_encode($json);
    echo "Items :";
    echo $jsonstring;

}
?>

`

0 个答案:

没有答案