如何在windows phone中读取JSON数组值



在尝试读取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数据。

问题是您的类与JSON数据不匹配。它们需要匹配,否则Json.NET将无法填充这些值,并且它们将保持为null。这是您所看到的错误最可能的原因。

试着把你的课做成这样:

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);
}

相关内容

  • 没有找到相关文章

最新更新