Dennis
Dennis

Reputation: 37

Flutter convert JSON string to multi-level list

I want to convert a string to multi-level list, but I cannot find a efficient way to do.

From String: [[1,2,3],[1,2]]

To List: List< List < int>>

Upvotes: 0

Views: 540

Answers (3)

philoniare
philoniare

Reputation: 1653

Shorter version:

import 'dart:convert';

void main() {
  var jsonMap = "[[1,2,3],[1,2]]";
  List<List<int>> items = (jsonDecode(jsonMap) as List).map((lst) => 
      (lst as List).map((i) => (i as int)).toList()).toList();
  print(items);
}

Upvotes: 0

Nidheesh MT
Nidheesh MT

Reputation: 1140

Try this as a funtion

List<List<int>> convert(String val){
    List<List<int>> list = [];
  jsonDecode(val).forEach((mainList) {
    List<int> subList = [];
    mainList.forEach((sList) {
      subList.add(sList);
    });
    list.add(subList);
  });
  return list;
}

Also import dart:convert;

Upvotes: 1

Naveen Avidi
Naveen Avidi

Reputation: 3073

String str = '[[1,2,3],[1,2]]';
  List<List<int>> list=[];
  for(String s in str.split('],[')){
    List<int> l = [];
    String formattedString = s.replaceAll('[','').replaceAll(']','');
    for(String innerS in formattedString.split(',')){
        l.add(int.parse(innerS));
      print(l);
    }
    list.add(l);
  }

Output: [[1, 2, 3], [1, 2]]

Upvotes: 0

Related Questions