2013-08-03 32 views
0

嘗試讀取JSON數組對象時遇到問題。如何讀取Windows Phone中的JSON數組值?

我正在使用PHP來創建JSON數據。

if (mysql_num_rows($result) > 0) { 
    // looping through all results 
    // products node 
    $response["records"] = array(); 
    //$response["products"] = array(); 

    while ($row = mysql_fetch_array($result)) 
    { 
     // temp user array 
     $record = array(); 
     $record["vehicleNo"] = $row["vehicleNo"]; 
     $record["vehicleType"] = $row["vehicleType"]; 
     $record["inTime"] = $row["inTime"]; 
     $record["outTime"] = $row["outTime"]; 
     $record["entryUser"] = $row["entryUser"]; 

     // push single record into final response array 
     array_push($response["records"], $record); 
    } 

    // success 
    $response["success"] = 1; 

    // echoing JSON response 
    echo json_encode($response); 
} 

上面的代碼返回以下JSON:

{"records":[{"vehicleNo":"6545","vehicleType":"Bike","inTime":"2013-08-01 18:11:20","outTime":"2013-08-01 19:27:55","entryUser":"srini"}],"success":1} 

我使用下面的代碼來解析JSON:

var rootObject = JsonConvert.DeserializeObject<MyBookList>(e.Result); 

Console.WriteLine(rootObject.success); 
MessageBox.Show(rootObject.success.ToString()); 
foreach (var re in rootObject.recordsss)// 
{ 
    Debug.WriteLine(re.value_record); 
    MessageBox.Show(re.value_record); 
} 

public class MyBookList 
{ 
    public string success { get; set; } 
    public MyRecords[] recordsss { get; set; } 
} 

public class MyRecords 
{ 
    public string value_record { get; set; } 
} 

但將不設置「對象引用到對象的實例「錯誤。

如何解決此問題並正確讀取JSON數據。

回答

2

問題是您的類與您的JSON數據不匹配。它們需要匹配,否則Json.NET將無法填充值,並且它們將保持爲空。這是您看到的錯誤的最可能原因。

嘗試使你的類是這樣的:

public class RootObject 
{ 
    public int success { get; set; } 
    public List<Record> records { get; set; } 
} 

public class Record 
{ 
    public string vehicleNo { get; set; } 
    public string vehicleType { get; set; } 
    public string inTime { get; set; } 
    public string outTime { get; set; } 
    public string entryUser { get; set; } 
} 

然後你可以反序列化和這樣的閱讀:

var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result); 

Console.WriteLine("success = " + rootObject.success); 
foreach (var re in rootObject.records) 
{ 
    Debug.WriteLine("vehicleNo = " + re.vehicleNo); 
    Debug.WriteLine("vehicleType = " + re.vehicleType); 
    Debug.WriteLine("inTime = " + re.inTime); 
    Debug.WriteLine("outTime = " + re.outTime); 
    Debug.WriteLine("entryUser = " + re.entryUser); 
} 
+0

你的代碼工作羅傑斯.... – selvam