在 Cascades 中解析 JSON

Parsing JSON in Cascades

我是 Blackberry 开发的新手,我一直在 JSON 解析。我已经学会了如何在 QML 中调用 Web 服务,但我不知道如何解析我获得的结果 JSON。谁能帮帮我?

提前致谢。

我的实际代码:

Button {
    id: newButton
    horizontalAlignment: HorizontalAlignment.Center
    verticalAlignment: VerticalAlignment.Center
    topMargin: ui.du(3)
    text: "Recharge"
    appearance: ControlAppearance.Primary

    onClicked: {
        getData()
    }
}

function getData() {
    var xmlhttp = new XMLHttpRequest();
    var url = "http://sb2.in/AppServices.asmx/getoperator";

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            myFunction(xmlhttp.responseText);
            //console.log(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

function myFunction(response) {
    var arr = JSON.parse(response);  
    console.log(response);     // (1) 
}

这是我在 (1) 中打印的 JSON 响应:

[{"CircleID":1,"CircleName":"Andhra Pradesh"},{"CircleID":4,"CircleName":"Assam"},{"CircleID":5,"CircleName":"Bihar"},{"CircleID":6,"CircleName":"Chennai"},{"CircleID":7,"CircleName":"Delhi"},{"CircleID":8,"CircleName":"Gujarat"},{"CircleID":9,"CircleName":"Himachal Pradesh"},{"CircleID":10,"CircleName":"Haryana"}]

如何正确解析此 JSON 响应?

使用DataSource.

在 QML 的顶部添加 import bb.data 1.0

attachedObjects: [
    DataSource {
      id: dataSource
      source: "http://mywebsite.com"
      type: DataSourceType.Json

      onDataLoaded: {
          //data is already parsed!
          console.log("Data: " + JSON.stringify(data));
      }
   }
]
onCreationCompleted: {
    dataSource.load(); 
}

将此添加到您的 .pro 文件中 LIBS += -lbbdata

谢谢@BaCaRoZzo。

网络服务和json解析:

 function getCircle() {
                var xmlhttp = new XMLHttpRequest();
                var url = "http://sb2.in/AppServices.asmx/getRecharge";

                xmlhttp.onreadystatechange=function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        circleFunction(xmlhttp.responseText);

                    }
                }
                xmlhttp.open("GET", url, true);
                xmlhttp.send();
            }
            function circleFunction(circleresponse){
                var circle = JSON.parse(circleresponse);  
                // console.log(circleresponse);// json 
                for (var k = 0; k< circle.length; k++) {
                    var circles = circle[k];
                    console.log("CircleName"+circles.CircleID);
                    console.log("CircleName"+circles.CircleName);

                }
            }

@BaCaRoZzo link: Javascript how to parse JSON array