首页 > 解决方案 > 如何在飞镖颤振中将json字符串转换为json对象?

问题描述

我有这样的字符串,

{id:1, name: lorem ipsum, address: dolor set amet}

我需要将该字符串转换为 json,我如何在 dart flutter 中做到这一点?非常感谢你的帮助。

标签: jsonstringflutterdartjsonconvert

解决方案


你必须使用json.decode. 它接受一个 json 对象并让您处理嵌套的键值对。我给你写个例子

import 'dart:convert';

// actual data sent is {success: true, data:{token:'token'}}
final response = await client.post(url, body: reqBody);

// Notice how you have to call body from the response if you are using http to retrieve json
final body = json.decode(response.body);

// This is how you get success value out of the actual json
if (body['success']) {
  //Token is nested inside data field so it goes one deeper.
  final String token = body['data']['token'];

  return {"success": true, "token": token};
}

推荐阅读