Home > Software engineering >  how to decode utf-8 cyrrilic text fron http response?
how to decode utf-8 cyrrilic text fron http response?

Time:01-29

How to decode this text using dart packages? i am using http package. Bacause the encoded string is cyrrilic and my http response is:

   {"items":[{"id":1,"title":"\u0421\u0430\u043c\u043e\u043a\u0430\u0442\u044b","slug":"samokaty"},{"id":2,"title":"\u0412\u0435\u043b\u043e\u0441\u0438\u043f\u0435\u0434\u044b","slug":"velosipedy"}

I am doing this:

  Future<ProductCategories?> fetchCategories() async {
    var response =
        await http.get(Uri.parse(_baseUrl   '/api/productCategories'));
    var jsonResponse = json.decode(response.body);
    print(response.body);
    try{
      return ProductCategories.fromJson(jsonResponse);
    }catch(e, s){
      log('error occurs', error: e, stackTrace: s);
    }
  }

CodePudding user response:

Try using

json.decode(utf8.decode(response.bodyBytes))

to convert the encoding to utf8

CodePudding user response:

See this answer I've tweaked it for null safety below:

void main() {
  final encoded = '\\u0421\\u0430\\u043c\\u043e\\u043a\\u0430\\u0442\\u044b';
  final expected = '\u0421\u0430\u043c\u043e\u043a\u0430\u0442\u044b';

  final unicodePattern = RegExp(r'\\u([0-9A-Fa-f]{4})');
  final result = encoded.replaceAllMapped(
    unicodePattern,
    (Match unicodeMatch) => String.fromCharCode(
      int.parse(unicodeMatch.group(1)!, radix: 16),
    ),
  );

  print(expected);
  print(result);
}

Prints:

Самокаты
Самокаты

CodePudding user response:

Try encode your response.body and decode again its printing below output :

var res = json.encode(response.body);
 print(json.decode(res));

output : hope this helps

{items: [{id: 1, title: Самокаты, slug: samokaty}, {id: 2, title: Велосипеды, slug: velosipedy}]}
  •  Tags:  
  • Related