如何解析JSON数组以获取单个数组元素

时间:2013-02-02 08:29:05

标签: javascript jquery asp.net web-services

我有这个返回JSON数组的web服务

 public string getLastDP(string accountID)
 {
    string connectionString = ConfigurationSettings.AppSettings["connectionString"].ToString();

    MySqlConnection connectionObj = new MySqlConnection(connectionString);
    List<lastDPElements> listOFElements = new List<lastDPElements>();
    try
    {
        connectionObj.Open();

        MySqlCommand cmd = new MySqlCommand("REPORTSERVER_ALL_LAST_DP_OF_DEVICE", connectionObj);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new MySqlParameter("acc", accountID));
        MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        while (dr.Read())
        {
            lastDPElements temp = new lastDPElements();
            temp.accountID = dr["accountID"].ToString();
            temp.address = dr["address"].ToString();
            temp.deviceID = dr["deviceID"].ToString();
            temp.displayName = dr["displayName"].ToString();
            temp.heading = double.Parse(dr["heading"].ToString());
            temp.inputMask = dr["inputMask"].ToString();
            temp.latitude = double.Parse(dr["latitude"].ToString());
            temp.longitude = double.Parse(dr["longitude"].ToString());
            temp.timestamp = Convert.ToDateTime(dr["timestamp"].ToString());
            listOFElements.Add(temp);
        }
        return new JavaScriptSerializer().Serialize(listOFElements);
    }
    catch
    {
        throw;
    }
    finally
    {
        connectionObj.Close();
        connectionObj.Dispose();
    }



}

服务返回的数组是

[{  "accountID":"rbTours",
"deviceID":"000020120504004",
"timestamp":"\/Date(1359720917000)\/",
"latitude":28.4337833,
"longitude":77.1048833,
"speedKPH":0,
"heading":130.44,
"altitude":0,
"address":"HCG CNG Station, Sector Road to Sector 56, DLF Ph. V, Gurgoan, Gurgaon, Haryana, 122002, India",
"odometerKM":null,
"displayName":"DL 1YC 7276",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"},{"accountID":"rbTours",
"deviceID":"000020120711002",
"timestamp":"\/Date(1358638851000)\/",
"latitude":28.610895,
"longitude":77.3269683,
"speedKPH":0,
"heading":253,
"altitude":0,
"address":"Gazipur Shamshan Ghat, Mayur Vihar III, Patparganj, East Delhi, National Capital Territory of Delhi, 110092, India",
"odometerKM":null,
"displayName":"DL1YC8576",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"},{"accountID":"rbTours",
"deviceID":"000020120618001",
"timestamp":"\/Date(1359721995000)\/",
"latitude":28.6345933,
"longitude":77.449505,
"speedKPH":0,
"heading":284.04,
"altitude":0,
"address":"National Highway 24 Bypass, B-Block, Lohia Nagar, Ghaziabad, Ghaziabad, Ghaziabad, Uttar Pradesh, 201001, India",
"odometerKM":null,
"displayName":"DL 1Y C6322",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"},{"accountID":"rbTours",
"deviceID":"000020120618002",
"timestamp":"\/Date(1359715788000)\/",
"latitude":28.4446867,
"longitude":77.0450667,
"speedKPH":0,
"heading":35.25,
"altitude":0,
"address":"NH8, Sec 38, Gurgoan, Gurgaon, Haryana, 122018, India",
"odometerKM":null,
"displayName":"UP16 AT 7410",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"},{"accountID":"rbTours",
"deviceID":"000020120711001",
"timestamp":"\/Date(1359693209000)\/",
"latitude":28.5384833,
"longitude":77.1915783,
"speedKPH":0,
"heading":288.26,
"altitude":0,
"address":"Aurobindo Marg, Qutab Institutional Area, Katwaria Sarai, South Delhi, National Capital Territory of Delhi, 110016, India",
"odometerKM":null,
"displayName":"UP16 AT7415",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"},{"accountID":"rbTours",
"deviceID":"356307040485566",
"timestamp":"\/Date(1359698595000)\/",
"latitude":28.5716512,
"longitude":77.136544,
"speedKPH":0,
"heading":0,
"altitude":0,
"address":"NH8, Palam, New Delhi, National Capital Territory of Delhi, 110021, India",
"odometerKM":null,
"displayName":"DL 1Y C9174",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"},{"accountID":"rbTours",
"deviceID":"000020120707001",
"timestamp":"\/Date(1359722004000)\/",
"latitude":28.6107633,
"longitude":77.327815,
"speedKPH":0,
"heading":299.16,
"altitude":0,
"address":"Sector 11, Noida, Ghaziabad, Ghaziabad, Uttar Pradesh, 201307, India",
"odometerKM":null,
"displayName":"DL 1YC 8577",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"},{"accountID":"rbTours",
"deviceID":"000020120623001",
"timestamp":"\/Date(1359722004000)\/",
"latitude":28.6425567,
"longitude":77.1736367,
"speedKPH":0,
"heading":124.77,
"altitude":0,
"address":"Patel Road, Patel Nagar, Kirti nagar, West Delhi, National Capital Territory of Delhi, India",
"odometerKM":null,
"displayName":"UP16 AT 8992",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"},{"accountID":"rbTours",
"deviceID":"000020120619001",
"timestamp":"\/Date(1359721984000)\/",
"latitude":28.43367,
"longitude":77.1048533,
"speedKPH":0,
"heading":154.8,
"altitude":0,
"address":"Centrum Plaza, Sector Road to Sector 56, DLF Ph. V, Gurgoan, Gurgaon, Haryana, 122002, India",
"odometerKM":null,
"displayName":"UP16 AT 9104",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"},{"accountID":"rbTours",
"deviceID":"000020120609005",
"timestamp":"\/Date(1359721996000)\/",
"latitude":28.6760217,
"longitude":77.2942033,
"speedKPH":0,
"heading":92.92,
"altitude":0,
"address":"National Highway 24, Shahdara, North East Delhi, National Capital Territory of Delhi, India",
"odometerKM":null,
"displayName":"DL1V A 8569",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"},{"accountID":"rbTours",
"deviceID":"000020120818004",
"timestamp":"\/Date(1359721960000)\/",
"latitude":27.1598883,
"longitude":78.0428533,
"speedKPH":0,
"heading":1.07,
"altitude":0,
"address":"The Silk Route Restaurant, SH62, Tajganj, Agra, Uttar Pradesh, 282001, India",
"odometerKM":null,
"displayName":"DL 1V A 8743",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"},{"accountID":"rbTours",
"deviceID":"000020120813001",
"timestamp":"\/Date(1359715794000)\/",
"latitude":28.613985,
"longitude":77.331255,
"speedKPH":0,
"heading":231.58,
"altitude":0,
"address":"Sector 11, Noida, Ghaziabad, Ghaziabad, Uttar Pradesh, 201307, India",
"odometerKM":null,
"displayName":"DL 1Y C6321",
"pushPinPath":null,
"temperature":null,
"inputMask":"0"}];

我如何解析它以获得我可以获得单个元素的格式的数据。我从以下脚本调用该服务。

function getData() {
            var accountObj = 'rbTours';
            $.ajax({
                url: "Services/GetData.asmx/getLastDP",
                type: "POST",
                dataType: "json",
                data: "{accountID:'" + accountObj + "'}",
                contentType: "application/json; charset=utf-8",
                success: function(response) {
                    functionOnSuccess(response.d);
                },
                error: function(e) {
                    alert(e);
                }
            });
            return false;
        }
        function functionOnSuccess(arrayOfElements) {
        var data=[];
        if (arrayOfElements != null && arrayOfElements != 'undefined') {
        for (var i = 0; i < arrayOfElements.length; i++) {
          var row = new Array();
          row[0] = response[i].latitude;
          row[1] = response[i].longitude;              
          data.addRow(row);
          }
          }
         alert(data);
        }

我应该如何在OnSuccess上以列表格式获取元素 我想得到像

这样的数据
var requiredValue=array[0].latitude etc

对不起我的英文..

4 个答案:

答案 0 :(得分:0)

问题是:您正尝试从该功能访问response

试试这个:

function functionOnSuccess(arrayOfElements) {
    var data=[];
    if (arrayOfElements != null && arrayOfElements != 'undefined') {
        for (var i = 0; i < arrayOfElements.length; i++) {
            var row = new Array();
            row[0] = arrayOfElements[i].latitude;
            row[1] = arrayOfElements[i].longitude;              
            data.addRow(row);
        }
    }
    alert(data);
}

答案 1 :(得分:0)

你可以发布你在firebug控制台中获得的json响应吗?

你不必手动解析json,当你设置dataType:'json' jquery为你解析响应时,你可以通过while循环的外观来访问json prop

success:function(data){
 console.log(data[0].lastDPElements);
}

你可以像上面那样遍历数据和道具......

答案 2 :(得分:0)

您可以按如下方式获取值。

  function getData() {
            var accountObj = 'rbTours';
            $.ajax({
                url: "Services/GetData.asmx/getLastDP",
                type: "POST",
                dataType: "json",
                data: "{accountID:'" + accountObj + "'}",
                contentType: "application/json; charset=utf-8",
                success: function(response) {
                    functionOnSuccess(response.d);
                },
                error: function(e) {
                    alert(e);
                }
            });
            return false;
        }
        function functionOnSuccess(arrayOfElements) {
        var data=[];
        if (arrayOfElements != null && arrayOfElements != 'undefined') {
          requiredValue=arrayOfElements[0].latitude; 
        }

编辑1

甚至你可以遍历你的收藏

   function functionOnSuccess(arrayOfElements) {
        var data=[];
        if (arrayOfElements != null && arrayOfElements != 'undefined') {
          for(i=0;i<arrayOfElements.length;i++)
          requiredValue=arrayOfElements[i].latitude; 
        }

编辑2

 function functionOnSuccess(arrayOfElements) {
       obj = JSON.parse(arrayOfElements);
       alert(obj.count);

看看有什么计数。

编辑3

 function functionOnSuccess(arrayOfElements) {
       obj = JSON.parse(arrayOfElements);
       alert(obj.length);

看看有什么计数。

答案 3 :(得分:0)

you have to try this 

 function getData() {
            var accountObj = 'rbTours';
            $.ajax({
                url: "Services/GetData.asmx/getLastDP",
                type: "POST",
                dataType: "json",
                data: "{accountID:'" + accountObj + "'}",
                contentType: "application/json; charset=utf-8",
                success: function(response) {
                    **functionOnSuccess((response.getLastDPResult).Toarray());**
                },
                error: function(e) {
                    alert(e);
                }
            });
            return false;
        }