0

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

4

1 回答 1

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);
}
于 2013-08-03T08:34:08.413 回答