如何在 dart/flutter 中提取 JSON 子数据
Posted
技术标签:
【中文标题】如何在 dart/flutter 中提取 JSON 子数据【英文标题】:How to extract JSON child data in dart / flutter 【发布时间】:2019-12-30 13:33:43 【问题描述】:我想提取 queryResult 的子值,即。 “你好。我是聊天机器人所以我们开始吧?”从 JSON 使用颤振
最终responseJson = json.decode(response.body);
print("DATA \n $responseJson['queryResult']");
JSON 数据 ===>
"responseId":"123456789",
"queryResult":
"queryText":"Hello",
"action":"input.welcome",
"parameters":
,
"allRequiredParamsPresent":true,
"fulfillmentText":"Greetings! How can I assist?",
"fulfillmentMessages":[
"text":
"text":[
"Hello there. I am chat bot So shall we get started?"
]
,
"quickReplies":
"quickReplies":[
"Yes",
"No"
]
],
"outputContexts":[
"name":"xyz",
"lifespanCount":5
],
"intent":
"name":"xyz",
"displayName":"Default Welcome Intent"
,
"intentDetectionConfidence":1,
"diagnosticInfo":
"webhook_latency_ms":5
,
"languageCode":"en"
,
"webhookStatus":
"message":"Webhook execution successful"
我无法读取 queryResult 的子数据使用
final responseJson = json.decode(response.body);
print("DATA \n $responseJson['queryResult']");
【问题讨论】:
您需要使用模式序列化您的 json 数据。这是链接flutter.dev/docs/development/data-and-backend/json 【参考方案1】:如果您想获得该特定行,则可以通过这种方式获得,但为了获得更多用途,最好像这里一样序列化 json:https://flutter.dev/docs/development/data-and-backend/json
print("DATA \n $responseJson['queryResult']['fulfillmentMessages'][0]['text']['text'][0]");
为了更容易理解路径:
print("DATA \n $
responseJson['queryResult']
['fulfillmentMessages'][0]
['text']
['text'][0]
"
);
整个代码和你的一样:
import 'dart:convert';
final responseBody = '"responseId":"123456789","queryResult":"queryText":"Hello","action":"input.welcome","parameters":,"allRequiredParamsPresent":true,"fulfillmentText":"Greetings! How can I assist?","fulfillmentMessages":["text":"text":["Hello there. I am chat bot So shall we get started?"],"quickReplies":"quickReplies":["Yes","No"]],"outputContexts":["name":"xyz","lifespanCount":5],"intent":"name":"xyz","displayName":"Default Welcome Intent","intentDetectionConfidence":1,"diagnosticInfo":"webhook_latency_ms":5,"languageCode":"en","webhookStatus":"message":"Webhook execution successful"';
void main()
final Map<String, dynamic> responseJson = json.decode(responseBody);
print("DATA \n $
responseJson['queryResult']
['fulfillmentMessages'][0]
['text']
['text'][0]
"
);
【讨论】:
以上是关于如何在 dart/flutter 中提取 JSON 子数据的主要内容,如果未能解决你的问题,请参考以下文章
如何在Dart / flutter中映射和显示嵌套的JSON?