首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不允许调用JSON对象中的JSON字段的统一JSON序列化程序

不允许调用JSON对象中的JSON字段的统一JSON序列化程序
EN

Stack Overflow用户
提问于 2020-03-10 19:30:29
回答 1查看 113关注 0票数 0

在这个问题上,我无法从刮过的网站调用嵌套的JSON对象。刮取过程工作得很好,但是JSON序列化部分是唯一的问题。我的代码如下所示:

代码语言:javascript
复制
private void GetHtmlAsync()
    {
        var url = "https://opentdb.com/api.php?amount=10";

        var httpClient = new HttpClient();
        var html = httpClient.GetStringAsync(url);

        DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(MyDetail));
        MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(html.Result));
        stream.Position = 0;
        MyDetail dataContractDetail = (MyDetail) jsonSerializer.ReadObject(stream);
        text.text = "" + dataContractDetail.results[1];
        //text.text = string.Concat("Test: ", dataContractDetail.question, " " + dataContractDetail.correct_answer);
    }

    public class MyDetail
    {
        [DataMember]
        public Dictionary<string, questions> results
        {
            get;
            set;
        }

        public class questions
        {
            public string question { get; set; }
            public string correct_answer { get; set; }

        }

        [DataMember]
        public string response_code
        {
            get;
            set;
        }
    }

这段代码是不起作用的代码,因为我试图通过执行"results1“来调用结果中的第一个对象,这将在我通过执行”结果1问题“向其附加”问题“之后返回一个错误。这个语法似乎是合理的,所以我不明白为什么它不起作用。我的JSON文件如下所示:

代码语言:javascript
复制
{
"response_code": 0,
"results": [
{
"category": "Entertainment: Video Games",
"type": "multiple",
"difficulty": "medium",
"question": "What is the name of the virus in &quot;Metal Gear Solid 1&quot;?",
"correct_answer": "FOXDIE",
"incorrect_answers": [
"FOXENGINE",
"FOXALIVE",
"FOXKILL"
]
},
{
"category": "Geography",
"type": "multiple",
"difficulty": "easy",
"question": "What is the official language of Costa Rica?",
"correct_answer": "Spanish",
"incorrect_answers": [
"English",
"Portuguese",
"Creole"
]
},
{
"category": "Entertainment: Video Games",
"type": "multiple",
"difficulty": "medium",
"question": "In Fallout 4, which type of power armor is first encountered in the early mission &quot;When Freedom Calls&quot; in a crashed Vertibird?",
"correct_answer": "T-45",
"incorrect_answers": [
"T-51",
"T-60",
"X-01"
]
},
{
"category": "Politics",
"type": "boolean",
"difficulty": "medium",
"question": "George W. Bush lost the popular vote in the 2004 United States presidential election.",
"correct_answer": "False",
"incorrect_answers": [
"True"
]
},
{
"category": "Entertainment: Video Games",
"type": "multiple",
"difficulty": "medium",
"question": "In &quot;Halo 2&quot;, what is the name of the monitor of Installation 05?",
"correct_answer": "2401 Penitent Tangent",
"incorrect_answers": [
"343 Guilty Spark",
"031 Exuberant Witness",
"252 Biodis Expolsion"
]
},
{
"category": "Entertainment: Books",
"type": "multiple",
"difficulty": "medium",
"question": "The book &quot;Fahrenheit 451&quot; was written by whom?",
"correct_answer": "Ray Bradbury",
"incorrect_answers": [
"R. L. Stine",
"Wolfgang Amadeus Mozart",
"Stephen King"
]
},
{
"category": "Entertainment: Cartoon & Animations",
"type": "multiple",
"difficulty": "hard",
"question": "In &quot;Rick and Morty&quot;, from which dimension do Rick and Morty originate from?",
"correct_answer": "C-137",
"incorrect_answers": [
"J1977",
"C-136",
"C500-a"
]
},
{
"category": "Entertainment: Video Games",
"type": "multiple",
"difficulty": "hard",
"question": "In which game did the character &quot;Mario&quot; make his first appearance?",
"correct_answer": "Donkey Kong",
"incorrect_answers": [
"Super Mario Bros.",
"Super Mario Land",
"Mario Bros."
]
},
{
"category": "Entertainment: Film",
"type": "multiple",
"difficulty": "hard",
"question": "What was Humphrey Bogart&#039;s middle name?",
"correct_answer": "DeForest",
"incorrect_answers": [
"DeWinter",
"Steven",
"Bryce"
]
},
{
"category": "Entertainment: Cartoon & Animations",
"type": "boolean",
"difficulty": "medium",
"question": "In &quot;Avatar: The Last Airbender&quot; and &quot;The Legend of Korra&quot;, Lavabending is a specialized bending technique of Firebending.",
"correct_answer": "False",
"incorrect_answers": [
"True"
]
}
]
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-11 07:01:38

您的代码中有许多问题。我不知道您正在使用的所有库,但下面是我将如何做到这一点。

首先,启动一个GetStringAsync,但是立即继续,而不等待结果。我不知道你正在使用的所有库,当然,也许它应该是那样的?

不过,我更愿意使用Unity的UnityWebRequest.Get

代码语言:javascript
复制
private void GetHtmlAsync()
{
    StartCoroutine(DownloadJson());
}


private IEnumerator DownloadJson()
{
    var url = "https://opentdb.com/api.php?amount=10";
    using(var uwr = UnityWebRequest.Get(url))
    {
        // send the request and wait for result
        yield return uwr.SendWebRequest();
        // Check for success!
        if(uwr.isNetworkError || uwr.isHttpError || !string.IsNullOrWhiteSpace(uwr.error))
        {
            Debug.LogError($"Download failed with {uwr.responseCode} reason: {uwr.error}", this);
            yield break;
        }

        var json = uwr.DownloadHandler.text;

        // ... se below
    }
}

同样,我不知道您的JSON库,但是您的类似乎与JSON数据结构不匹配(只需通过json2csharp干扰它)。

代码语言:javascript
复制
[Serializable]
public class Result
{
    public string category;
    public string type;
    public string difficulty;
    public string question;
    public string correct_answer;
    public List<string> incorrect_answers;
}

[Serializable]
public class MyDetail
{
    public int response_code;
    public List<Result> results;
}

对于统一,我将使用[Serializable],并删除所有{get;set},以便不使用属性,而使用字段。

然后,您可以简单地使用联合的JsonUtility

代码语言:javascript
复制
...
MyDetail dataContractDetail = JsonUtility.FromJson<MyDetail>(json);

然后,正如注释中提到的那样,c#中的数组索引是0-based,因此first元素应该是

代码语言:javascript
复制
var firstResult = dataContractDetail.results[0];

现在的问题是你想在你的短信上看到什么?firstResult不是string,而是一个有各种成员的类!例如,你可以像这样显示问题

代码语言:javascript
复制
text.text = firstResult.question;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60624677

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档