如何在flutter中将来自api的复杂json响应存储在本地数据库中? [英] How to store a complex json response from api in local database in flutter?

查看:389
本文介绍了如何在flutter中将来自api的复杂json响应存储在本地数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从api保存整个json响应。我尝试使用SQFLITE库进行存储,但是由于需要以表格式存储,因此我无法实现存储完整的json。我对扑扑很陌生。任何人都可以建议我如何实现这一目标。我在下面附上我的示例json供您参考。

I want to save the whole json response from api. I tried SQFLITE library to store but i cant able to achieve to store a complete json as it need to store in a table format. I'm very new to flutter. can any body suggest how can i achieve this. Below i'm attaching my sample json for your reference.

{
  "result": {
    "allitems": {
      "answered_status": 0,
      "list_items": [
        {
          "is_answered": false,
          "options": [
            {
              "image_url": "assets/images/orders/jersey.jpg",
              "description": "Jersey",
              "title": "Jersey",
              "price": 23
            },
            {
              "image_url": "assets/images/orders/bat.png",
              "description": "Bat",
              "title": "Bat",
              "price": 5
            },
          ]
        }
      ],
      "no_of_items": 12,
      "title": "ALL"
    }

  },
  "status_code": 200
}


推荐答案

在我的评论中,我对 SharedPreferences 是错误的。事实证明, SharedPreferences 不支持 Map< dynamic,dynamic> ,并且最多支持 List< ; String>

I was wrong about SharedPreferences in my comment. Turns out SharedPreferences doesn't support Map<dynamic, dynamic> and only up to List<String> yet.

因此您可以使用数据库管理包 sembast 由制造 SQFLite 的同一个人制造。

So you can use a database management package sembast made by the same guy who made SQFLite.

您可以通过链接获取帮助将JSON对象转换为 Map ,反之亦然。

You can get help with this link to convert JSON objects to Map and vice-versa.

编辑-

您可以执行以下操作-

import 'package:sembast/sembast.dart';

Map<dynamic, dynamic> sampleMap;

// Skipping this part
sampleMap = // Retrive and convert JSON to Map

// A sample DB in the current directory
String dbPath = 'sample.db';
DatabaseFactory dbFactory = databaseFactoryIo;

// We use the database factory to open the database
Database db = await dbFactory.openDatabase(dbPath);

var store = intMapStoreFactory.store();

// Storing Map to DB
var key = await store.add(db, sampleMap);

// Retrieving values back
var record = await store.record(key).getSnapshot(db);

// From your provided sample JSON in question
var value = record["result"]["allitems"]["list_items"][0]["options"]["image_url"];

print(value);
// value = 'assets/images/orders/jersey.jpg'

类似地,您可以探索该软件包的文档以进行更多数据操作。

Similarly, you can explore the documentation of the package for more data operations.

这篇关于如何在flutter中将来自api的复杂json响应存储在本地数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆