如何更新 JSON 值。我正在使用带有 REST API 的 flutter 来更改数据,但我正在努力如何刷新我的 JSON 数据对不起 friend 我对 flutter 不太了解所以请帮助我解决这个问题请在下面找到 JSON 的对象:
{
id: 1,
clef: "Y8F5eEo0",
IndiceSensibilite: "0.04",
Objectif: "1.00"
}
我想使用文本字段更新 IndiceSensibilite 的值。 我在这里是为了进一步澄清。 如果有人愿意帮助我,我将不胜感激。
最佳答案
您可以将 JSON 转换为对象,进行修改并返回 JSON:
import 'dart:convert'; // make sure you imported this library
String jsonValue = '{"id": 1, "clef": "Y8F5eEo0", "indiceSensibilite": "0.04", "objectif": "1.00" }'; // original JSON
使用 Future 将其转换为对象:
Future<ToObject> jsonToObject() async {
var parse = json.decode(jsonValue);
return ToObject.parseJson(parse);
}
您的对象(在我的例子中是 ToObject)将具有以下模型和方法:
class ToObject {
int id;
String clef;
String indiceSensibilite;
String objectif;
ToObject({this.id, this.clef, this.indiceSensibilite, this.objectif});
factory ToObject.parseJson(Map<String, dynamic> json) => ToObject(
id: json['id'], clef: json['clef'], indiceSensibilite: json['indiceSensibilite'], objectif: json['objectif']);
Map<String, dynamic> toJson() =>
{'id': id, 'clef': clef, 'indiceSensibilite': indiceSensibilite, 'objectif': objectif};
}
我使用 FutureBuilder 获取数据,修改值并返回 JSON:
FutureBuilder<ToObject>(
future: jsonToObject(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
var object = snapshot.data;
object.indiceSensibilite = "43.00";
return Text(json.encode(object.toJson()));
} else {
return Text("Loading...");
}
},
)
您的最终结果是一个修改后的 JSON,您可以随意使用:
关于json - 如何使用 flutter 更新 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56728335/