Home > database >  Json to Dart List
Json to Dart List

Time:06-04

I'm trying to use this json for my project.

https://github.com/altafc22/csc_picker/blob/master/lib/assets/country.json

However, I don't want to use it directly in my project cuz it's a big file and want to specialize it a little bit. Is there a way to convert this json to Dart lists?

CodePudding user response:

Try out this

Future getResponse() async {
    var res = await rootBundle.loadString('packages/country_state_city_picker/lib/assets/country.json'); // Use your url
    return jsonDecode(res);
  }
  
  and fetch list like below:
  
   var countryres = await getResponse() as List;
   print(countryres);

CodePudding user response:

You can try this code. Maybe this will help you...
The list code will be saved to file lib/data.dart. I warn you, the size will be large.

import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;

void main() async {
  final url =
      'https://raw.githubusercontent.com/altafc22/csc_picker/master/lib/assets/country.json';
  final response = await http.get(Uri.parse(url));
  final data = jsonDecode(response.body);
  final result = getAsCode(data);
  final file = 'lib/data.dart';
  File(file).writeAsStringSync('const data = $result;');
}

String escapeString(String text, [bool quote = true]) {
  text = text.replaceAll('\\', r'\\');
  text = text.replaceAll('\b', r'\b');
  text = text.replaceAll('\f', r'\f');
  text = text.replaceAll('\n', r'\n');
  text = text.replaceAll('\r', r'\r');
  text = text.replaceAll('\t', r'\t');
  text = text.replaceAll('\v', r'\v');
  text = text.replaceAll('\'', '\\\'');
  text = text.replaceAll('\$', r'\$');
  if (!quote) {
    return text;
  }

  return '\'$text\'';
}

String getAsCode(Object? value) {
  final result = tryGetAsCode(value);
  if (result != null) {
    return result;
  }

  throw StateError('Unsupported type: ${value.runtimeType}');
}

String? tryGetAsCode(Object? value) {
  if (value is String) {
    final escaped = escapeString(value);
    return escaped;
  } else if (value is bool) {
    return '$value';
  } else if (value is num) {
    return '$value';
  } else if (value == null) {
    return '$value';
  } else if (value is Enum) {
    return '${value.runtimeType}.${value.name}';
  } else if (value is List) {
    final values = [];
    for (var item in value) {
      final code = tryGetAsCode(item);
      values.add(code);
    }

    return '[${values.join(', ')}]';
  } else if (value is Set) {
    final values = [];
    for (var item in value) {
      final code = tryGetAsCode(item);
      values.add(code);
    }

    return '{${values.join(', ')}}';
  } else if (value is Map) {
    final values = [];
    for (var key in value.keys) {
      final k = tryGetAsCode(key);
      final v = tryGetAsCode(value[key]);
      values.add('$k: $v');
    }

    return '{${values.join(', ')}}';
  }

  return null;
}

  • Related