【问题标题】:parse webapi object to similar object将 webapi 对象解析为相似对象
【发布时间】:2015-02-01 10:49:06
【问题描述】:

我在 Unity 中使用 WWW 从我的 webapi 获取一些数据,现在我想在我的 Unity C# 脚本中将 json 解析为我的对象。

这是我的回调方法:

private void answersCallback(WWW wwwData){
    JSONNode questionJSON = JSONNode.Parse (wwwData.text);
    QuestionThemeRequest q = new QuestionThemeRequest();
    q.QuestionTheme = questionJSON["QuestionTheme"];
    Debug.Log (q.QuestionTheme);
}

在这里,我只将 json 对象中的 QuestionTheme 解析为我在 questionthemerequest 中的特定属性。

但是,如果我在 wwwData 中获取的对象看起来与 QuestionThemeRequest 相同,并且我想解析整个对象而不是一个属性怎么办?我该怎么做?

【问题讨论】:

    标签: c# json parsing object unity3d


    【解决方案1】:

    如果您想要一个包含返回 JSON 的所有值的 QuestThemeRequest 对象,则需要将所有值读入该对象。然后要么返回该对象,要么为其分配一些成员属性。

    private void answersCallback(WWW wwwData){
        JSONNode questionJSON = JSONNode.Parse (wwwData.text);
        QuestionThemeRequest q = new QuestionThemeRequest();
        q.QuestionTheme = questionJSON["QuestionTheme"];
    
        //Assign all the other possible values to q
        Debug.Log (q.QuestionTheme);
    
        return q;
    }
    

    【讨论】:

    • 但在问题themerequest 我有一个列表。我应该遍历列表并分配每个属性吗?似乎是一种非常奇怪的方法。必须有某种方法来解析整个对象?
    • 原始 JSON 被转换为两种类型的对象。根据 Json.org (json.org):A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. 我不相信有办法将 JSONNode 转换为 QuestThemeRequest。我认为您确实必须遍历它。
    猜你喜欢
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 2019-12-07
    相关资源
    最近更新 更多