Search code examples
jsonfluttersharedpreferencesjsondecoder

i want to convert String into Json string in flutter?


I have decoded my response.body i.e var jsonData = jsonDecode(response.body); and its working fine But when i convert it into object and saved into local storage using sharedpref like this

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());

It stored in it And whenever i try to decode this its not working i.e

 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,
                });
}

its not the same as before,its showing error and after fixing some 1st element of string '[' is showing. please help with this thanks in advance.


Solution

  • Change your ExpertCategory model to this:

    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;
      }
    }
    

    For your LocalStorage class, there are two approaches to setting your data into SharedPreferences. One using setString, the other being setStringList since you are storing the list of categories.

    Checkout both approaches below.

    APPROACH 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());
      }
    }
    

    APPROACH 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());
      }
    }
    

    And finally you set your data into the SharedPreferences using

    localStorage.setCategoryData(categoryList);