gpt4 book ai didi

json - 在Dart中将数据添加到JSON文件

转载 作者:行者123 更新时间:2023-12-03 04:15:29 24 4
gpt4 key购买 nike

  • 我有一个Json文件,该文件具有一些用户数据作为数组,我能够在flutter项目中读取这些数据,但是我想做的是从我从flutter应用程序中从textfield接收的数据中添加其他用户。
  • 谁能告诉我该怎么做?提前致谢。

  • 我的Json文件看起来像这样。
        {
    "users": [
    {
    "id": 1,
    "username": "steve",
    "password": "captainamerica"
    }
    ]
    }

    并且我必须添加另一个用户,其ID为-2,用户名-Tony和密码-Ironman。

    最佳答案

    我尝试向您展示如何将JSON映射到OBJECT,然后将新用户添加到users对象,然后再添加到JSON。

    这是完整的代码:

    如果您有任何疑问,请询问:

    import 'dart:convert';
    import 'package:flutter/foundation.dart';
    import 'package:flutter/material.dart';

    UsersPodo _usersPodo; // Users object to store users from json

    // A function that converts a response body into a UsersPodo
    UsersPodo parseJson(String responseBody) {
    final parsed = json.decode(responseBody);
    return UsersPodo.fromJson(parsed);
    }

    class Demo extends StatefulWidget {
    @override
    _Demo createState() => _Demo();
    }

    class _Demo extends State<Demo> {
    final String localJson = '''
    {
    "users": [
    {
    "id": 1,
    "username": "steve",
    "password": "captainamerica"
    }
    ]
    }'''; // local json string

    Future<UsersPodo> fetchJSON() async {
    return compute(parseJson, localJson);
    }

    Widget body() {
    return FutureBuilder<UsersPodo>(
    future: fetchJSON(),
    builder: (context, snapshot) {
    return snapshot.hasError
    ? Center(child: Text(snapshot.error.toString()))
    : snapshot.hasData
    ? _buildBody(usersList: snapshot.data)
    : Center(child: Text("Loading"));
    },
    );
    }

    Widget _buildBody({UsersPodo usersList}) {
    _usersPodo = usersList;

    _usersPodo.users.add(new Users(id: 1, username: "omishah", password: "somepassword")); // add new user to users array

    return Text(_usersPodo.users[1].toJson().toString()); // just for the demo output

    // use _usersPodo.toJson() to convert the users object to json
    }

    Widget build(BuildContext context) {
    return Scaffold(
    backgroundColor: Color(0xfff3f3f3),
    appBar: AppBar(backgroundColor: Colors.red[900], title: Text("DEMO")),
    body: body());
    }
    }

    // PODO Object class for the JSON mapping
    class UsersPodo {
    List<Users> users;

    UsersPodo({this.users});

    UsersPodo.fromJson(Map<String, dynamic> json) {
    if (json['users'] != null) {
    users = new List<Users>();
    json['users'].forEach((v) {
    users.add(new Users.fromJson(v));
    });
    }
    }

    Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.users != null) {
    data['users'] = this.users.map((v) => v.toJson()).toList();
    }
    return data;
    }
    }

    class Users {
    int id;
    String username;
    String password;

    Users({this.id, this.username, this.password});

    Users.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    username = json['username'];
    password = json['password'];
    }

    Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['username'] = this.username;
    data['password'] = this.password;
    return data;
    }
    }

    关于json - 在Dart中将数据添加到JSON文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59279156/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com