您的问题的问题在于,我们甚至不知道您传入数据的一般结构。作为一个社区,我们不需要知道一个实际的例子。即使是伪造的数据也足够了。
话虽如此,我将尝试为您提供一些示例,说明您的传入数据可能是什么,以及您如何做您想做的事情。
传入的 JSON 对象
假设您的传入数据如下所示:
{
"data1": {
"subdata1":"subvalue1",
"subdata2":"subvalue2",
"subdata3":3,
"subdata4":{
"subsubdata1":"subvalue1"
}
},
"data2": {
"subdata1":"subvalue1",
"subdata2":"subvalue2",
"subdata3":3,
"subdata4":{
"subsubdata1":"subvalue1"
}
}
}
在这种情况下,您可以使用 jsonDecode,并且仍然能够计算键并返回关联的对象列表,如下所示:
void consumeResponse(http.Response response) {
// decode the entire response string
final Map<String, dynamic> rawObject = jsonDecode(response.body);
// count the records in the response
final int recordCount = rawObject.keys.length;
// create an array of the data in each top level object key (but you lose the top level key name)
final List<dynamic> records = List<dynamic>.from(rawObject.values);
}
传入的 JSON 对象数组
假设您的 json 实际上已经在一个 json 数组中,并且您的响应如下所示:
[
{
"data1": {
"subdata1":"subvalue1",
"subdata2":"subvalue2",
"subdata3":3,
"subdata4":{
"subsubdata1":"subvalue1"
}
}
},
{
"data2": {
"subdata1":"subvalue1",
"subdata2":"subvalue2",
"subdata3":3,
"subdata4":{
"subsubdata1":"subvalue1"
}
}
}
]
然后你可以用这个函数完成同样的事情:
void consumeResponse(http.Response response) {
// decode the entire response string. this will auto-magically produce a List<dynamic>
final List<dynamic> records = jsonDecode(response.body);
// count the records in the response
final int recordCount = records.length;
}
带有数据子列表的传入 JSON 对象
在某些情况下,您可能会在包装 json 对象中嵌入一个结果列表,该对象还包含一些关于您的查询的额外元数据。在这种情况下,您的数据可能如下所示:
{
"meta": {
"limit": 2,
"offset": 1,
"total": 47
},
"results": [
{
"data1": {
"subdata1":"subvalue1",
"subdata2":"subvalue2",
"subdata3":3,
"subdata4":{
"subsubdata1":"subvalue1"
}
}
},
{
"data2": {
"subdata1":"subvalue1",
"subdata2":"subvalue2",
"subdata3":3,
"subdata4":{
"subsubdata1":"subvalue1"
}
}
}
]
}
在这种情况下,您可能希望在键 results 中的子列表上运行相同的函数。您也可以使用类似的功能来做到这一点:
void consumeResponse(http.Response response) {
// decode the entire response string
final Map<String, dynamic> rawObject = jsonDecode(response.body);
// create the List<dynamic> from the results list in the sub object
final List<dynamic> records = rawObject['results'];
// count the records in the response
final int recordCount = records.length;
}
结束
希望,即使您的问题很模糊,但至少其中一种场景是您可以使用的。如果可以的话,创建一些可以共享的“模拟数据”和/或“模拟代码”总是更好。该社区使用所有可用数据来构建他们的答案。您提供给我们的数据越多,您得到的答案就越好。