解析 JSON 数据 QML

Maj*_*-pl 3 database qml

与主题一样,我正在尝试将此 json 数据解析到我的 QML 项目中

链接:http : //www.rad.io/info/menu/valuesofcategory?category=_genre

所以我有 188 个元素的列表,但不知道如何获取每个元素的值...

是我在此示例中使用的 JSONListModel 组件的链接

这是qml代码:

import QtQuick 2.0
import Ubuntu.Components 1.1
import "../components"
import Ubuntu.Components.ListItems 1.0 as ListItem


Page {
    title: i18n.tr("by Genre")


    JSONListModel {
        id: json
        source: "http://www.rad.io/info/menu/valuesofcategory?category=_genre"
        query: "$"
    }


    UbuntuListView {
        height: parent.height
        width: parent.width
        clip: true
        model: json.model
        cacheBuffer: contentHeight


        delegate: ListItem.Standard {
            text: index + "  " + indexValue
        }

    }    

}
Run Code Online (Sandbox Code Playgroud)

Rob*_*oll 5

我不是 JSONListModel 方面的专家,所以我可能会弄错,但它似乎希望迭代对象列表。您从 rad.io 获得的是一个字符串列表,这似乎是您遇到问题的原因。但是由于您不需要对结果进行任何花哨的处理,因此手动滚动它很容易。

您想要做的是将响应解析为列表(使用JSON.parse)。然后你可以浏览列表的元素。对于每个,您创建一个对象并将其附加到ListModel. 请注意,ListModel需要对象,而不是字符串。然后委托可以引用这些对象的属性。

示例代码:

import QtQuick 2.0
import Ubuntu.Components 1.1
import Ubuntu.Components.ListItems 1.0 as ListItem

MainView {
    width: 300
    height: 600
    property string source: "http://www.rad.io/info/menu/valuesofcategory?category=_genre"

    ListModel {
        id: listModel
    }

    Component.onCompleted: {
        var xhr = new XMLHttpRequest;
        xhr.open("GET", source);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                var list = JSON.parse(xhr.responseText);
                listModel.clear();
                for (var i in list)
                    listModel.append({ "genre": list[i] });
            }
        }
        xhr.send();
    }

    Page {
        title: i18n.tr("by Genre")

        UbuntuListView {
            height: parent.height
            width: parent.width
            clip: true
            model: listModel
            cacheBuffer: contentHeight

            delegate: ListItem.Standard {
                text: index + "  " + genre
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

让我花点时间提醒您发布简短、独立、正确的示例的重要性。您发布的代码无法运行不是因为解析 JSON 有任何问题,而是因为 aTab不能是顶级小部件。任何试图帮助您的人都必须先弄清楚这一点,然后才能解决真正的问题。

此外,当使用非默认组件时,例如JSONListModel,请注意这一事实并指出可以找到它的位置。重现问题所需的工作越少越好。