我想在颤振中将字符串转换为 Json 字符串?

时间:2021-03-05 14:03:06

标签: json flutter sharedpreferences jsondecoder

我已经解码了我的 response.bodyvar jsonData = jsonDecode(response.body); 并且它工作正常 但是当我使用 sharedpref 将其转换为对象并保存到本地存储中时

if (response.statusCode == 200) {
      jsonData['categoryList'].forEach((data) => {
            categoryList.add(new ExpertCategory(
                id: jsonData['_id'],
                color: jsonData['color'],
                type: jsonData['category_name'],
                icon: ":)"))
          });
      print(categoryList) ;   
      localStorage.setCategoryData(categoryList.toString());

它存储在其中并且每当我尝试对其进行解码时它都不起作用,即

 localStorage.getCategoryData().then((data) => {
         userMap =  jsonDecode(data),
          
        });

class LocalStorage {
Future setCategoryData(data) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString('category', data);
  
  }

  Future getCategoryData() async {
    final prefs = await SharedPreferences.getInstance();
    final category = prefs.getString('category');
    return category;
  }
}
import 'package:flutter/foundation.dart';

class ExpertCategory {
  final String  id;
  final String  type;
  final String  icon;
  final String  color;

const ExpertCategory( {
                  @required this.id,
                  @required this.type,
                  @required this.icon,
                  @required this.color,
                });
}

它与以前不同,它显示错误并且在修复字符串 '[' 的第一个元素之后 正在显示。请提前帮助解决这个问题。

1 个答案:

答案 0 :(得分:1)

将您的 ExpertCategory 模型更改为:

import 'package:flutter/material.dart';

class ExpertCategory {
  String id;
  String type;
  String icon;
  String color;

  ExpertCategory(
      {@required this.id,
      @required this.type,
      @required this.icon,
      @required this.color});

  ExpertCategory.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    type = json['type'];
    icon = json['icon'];
    color = json['color'];
  }

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

对于您的 LocalStorage 类,有两种方法可以将您的数据设置为 SharedPreferences。一个使用 setString,另一个使用 setStringList,因为您要存储类别列表。

检查以下两种方法。

方法 1

class LocalStorage {
  Future setCategoryData(List<ExpertCategory> data) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString(
        'category', jsonEncode(data.map((e) => e.toJson()).toList()));
  }

  Future<List<ExpertCategory>> getCategoryData() async {
    final prefs = await SharedPreferences.getInstance();
    final category = prefs.getString('category');
    return List<ExpertCategory>.from(
        List<Map<String, dynamic>>.from(jsonDecode(category))
            .map((e) => ExpertCategory.fromJson(e))
            .toList());
  }
}

方法 2

class LocalStorage {
  Future setCategoryData(List<ExpertCategory> data) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setStringList('category',
        List<String>.from(data.map((e) => jsonEncode(e.toJson())).toList()));
  }

  Future<List<ExpertCategory>> getCategoryData() async {
    final prefs = await SharedPreferences.getInstance();
    final category = prefs.getStringList('category');
    return List<ExpertCategory>.from(
        category.map((e) => ExpertCategory.fromJson(jsonDecode(e))).toList());
  }
}

最后,您使用

将数据设置到 SharedPreferences
localStorage.setCategoryData(categoryList);