简体   繁体   English

将字符串反序列化为JSON对象时出错

[英]Error deserialising string into JSON object

I have a php file which reads a .txt file and sends it via a php server to ac# unity script. 我有一个php文件,该文件读取.txt文件,并通过php服务器将其发送到ac#统一脚本。 Below is a snippet of the text file showing the first 3 lines: 下面是显示前三行的文本文件的片段:

{ "lemma" : "aljotta", "gloss" : "Fisħ soup" }
{ "lemma" : "arguzin", "gloss" : "Slave driver" }
{ "lemma" : "armunjaka", "gloss" : "Armunjaka" }

This is the php script: 这是PHP脚本:

<?php
$file = fopen("lemmas.txt", "r");
echo fread($file, filesize("lemmas.txt"));
fclose($file);
?>

In ac# script, the text is returned and each line is separated into an array (string[] lines) slot as seen below: 在ac#脚本中,返回文本,并将每一行分成一个数组(string []行)插槽,如下所示:

IEnumerator GetTextFromFile()
    {
        bool succcessful = true;
        WWWForm form = new WWWForm();
        WWW www = new WWW("http://localhost:9000/tounity.php", form);

        yield return www;

        if(www.error != null)
        {
            succcessful = false;
        }
        else
        {
            succcessful = true;
        }

        if (succcessful)
        {
            populateWordList(www.text);
        }
    }

 void populateWordList(string text)
    {
        string[] textArray = text.Split('\n');
        wordsList = gameDatabase.GetWords(textArray);
    }

The array is then passed to a method which deserializes each line into an object of class GameDatabase as seen in the image below: 然后将该数组传递给一个方法,该方法将每行反序列化为GameDatabase类的对象,如下图所示:

public string lemma { get; set; } 
public string gloss { get; set; }

public GameDatabase(string lemma, string gloss)
{
    this.lemma = lemma;
    this.gloss = gloss;
}

public  ArrayList GetWords(string[] lines)
{
    foreach (string line in lines)
    {

        GameDatabase gd = JsonConvert.DeserializeObject<GameDatabase>(line);
        lemmasAndGlossesList.Add(new GameDatabase(gd.lemma, gd.gloss));
    }

    foreach(GameDatabase line in lemmasAndGlossesList)
    {
        Debug.Log(line.lemma + "------" + line.gloss);
    }

    return lemmasAndGlossesList;
}

The error occurs in GameDatabase gd = JsonConvert.DeserializeObject<GameDatabase>(line); 该错误发生在GameDatabase gd = JsonConvert.DeserializeObject<GameDatabase>(line); and returns 并返回

JsonReaderException: Unexpected character encountered while parsing value: . Path '', line 0, position 0.

I have searched extensively, however, haven't found anything that works. 我进行了广泛的搜索,但是没有找到任何有效的方法。 Any help would be greatly appreciated. 任何帮助将不胜感激。 It is worth noting that this problem doesn't happen when loading the text file directly into unity without using php. 值得注意的是,不使用php将文本文件直接加载为unity时,不会发生此问题。


EDIT 编辑


When using the vs debugger this is the value in the line to be deserialized: 使用vs调试器时,这是要反序列化的行中的值:

在此处输入图片说明

The JSON visualiser of Visual Studio 2019 however reports this: 但是,Visual Studio 2019的JSON可视化工具报告以下内容:

在此处输入图片说明

Thanks to Jonathon K's comment and your reply we can see the data returned by the PHP script starts with a BOM : the first three bytes. 感谢Jonathon K的评论和您的回复,我们可以看到PHP脚本返回的数据以BOM表开头:前三个字节。 This nice article explains how to handle such data properly. 这篇不错的文章介绍了如何正确处理此类数据。 In short: use a StreamReader to read the data. 简而言之:使用StreamReader读取数据。

This little program demonstrates how it could work with your data: 这个小程序演示了如何处理您的数据:

using System;
using Newtonsoft.Json;
using System.IO;


public class Program
{
    public static void Main()
    {
        var bytes = new byte[] {
            0xEF,0xBB,0xBF,0x7B,0x20,0x22,0x6C,0x65,0x6D,0x6D,0x61,0x22,
            0x20,0x3A,0x20,0x22,0x61,0x72,0x67,0x75,0x7A,0x69,0x6E,0x22,
            0x2C,0x20,0x22,0x67,0x6C,0x6F,0x73,0x73,0x22,0x20,0x3A,0x20,
            0x22,0x53,0x6C,0x61,0x76,0x65,0x20,0x64,0x72,0x69,0x76,0x65,
            0x72,0x22,0x20,0x7D};

        string json;
        using(var ms = new MemoryStream(bytes))
        using(var sr = new StreamReader(ms))
        {
            json = sr.ReadToEnd();
            Console.WriteLine(json);
        }

        // I'm using dynamic here. In your case you can use GameDatabase
        dynamic obj = JsonConvert.DeserializeObject(json);
        Console.WriteLine(obj.lemma);
    }
}

Output: 输出:

{ "lemma" : "arguzin", "gloss" : "Slave driver" }
arguzin

I dont know the c# sintax but this will work. 我不知道C#的sintax,但这会起作用。

change your JSON file. 更改您的JSON文件。

[
    { "lemma" : "aljotta", "gloss" : "Fisħ soup" },
    { "lemma" : "arguzin", "gloss" : "Slave driver" },
    { "lemma" : "armunjaka", "gloss" : "Armunjaka" }
]

apply JsonConvert.DeserializeObject to www.text JsonConvert.DeserializeObject应用于www.text

for (GameDatabase line in JsonConvert.DeserializeObject<GameDatabase[]>(www.text)){
    Debug.Log(line.lemma + "------" + line.gloss);
}

Maybe my c# syntax is wrong but i would that u understand my idea 也许我的C#语法是错误的,但是我会让你理解我的想法

I think it's possible that you're going about deserialization wrong by using JsonConvert. 我认为使用JsonConvert可能会使反序列化出错。

Instead, read up on this documentation and try to use the Unity functions: https://docs.unity3d.com/Manual/JSONSerialization.html 相反,请阅读此文档并尝试使用Unity功能: https : //docs.unity3d.com/Manual/JSONSerialization.html

For starters, you're defining lemma and gloss incorrectly if you're looking to use them for deserializing JSON in Unity. 对于初学者,如果要使用它们在Unity中反序列化JSON,则定义的引理和光泽不正确。 See this answer for more info: Serialize and Deserialize Json and Json Array in Unity 有关更多信息,请参见以下答案: 在Unity中序列化和反序列化Json和Json Array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM