Bora Tan Demir
Bora Tan Demir

Reputation: 71

Dart Json UTF-8 Decode

I need to decode the data I receive as utf8. The codes are like this

Future<Products> Get Product() async {
     var response = await http.get(url);
     var decodedJson = json.decode(response.body);
     products = Products.fromJson(decodedJson);
     return products;
   }

I tried the solutions I saw. One of them told me to do it like this

 var response = await http.get(url,headers: {'Content-Type': 'application/json'});
 var decodedJson = json.decode(utf8.decode(response.bodyBytes));

When I do this, I get the following

errorException has occurred.
FormatException (FormatException: Missing extension byte (at offset 554))

And it's look like enter image description here

Upvotes: 3

Views: 5624

Answers (4)

Dominik Roszkowski
Dominik Roszkowski

Reputation: 2543

You can also used specialized Utf8Decoder fused with JsonDecoder to receive the Map<String,dynamic>

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

// bodyBytes comes from http.Response class
final map = const Utf8Decoder().fuse(const JsonDecoder()).convert(httpResponse.bodyBytes) as Map<String, dynamic>?;

In that case the Dart SDK creates a more efficient decoder _JsonUtf8Decoder (see source code here)

Upvotes: 0

Ndiaga GUEYE
Ndiaga GUEYE

Reputation: 391

 // Decode the response body explicitly in UTF-8 to handle special characters
  dynamic responseJson = jsonDecode(utf8.decode(response.bodyBytes));

Upvotes: 0

Renis1235
Renis1235

Reputation: 4700

Back-End Solution

I had the same problem and solved it by setting Character Encoding on the Back-End side of my application.

This can be done by appending the Content-Type Header like this:

Content-Type: application/json;charset=UTF-8

There are different ways to achieve this depending on your Framework/Implementation.

Unfortunately, this answer is not suitable for Flutter per se.

Upvotes: 3

akram abdullah
akram abdullah

Reputation: 164

Try this code

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<Products> Get Product() async {
      final response = await http
          .get(Uri.parse(url));
    
      if (response.statusCode == 200) {
        // If the server did return a 200 OK response,
        // then parse the JSON.
        return Products.fromJson(jsonDecode(response.body));
      } else {
        // If the server did not return a 200 OK response,
        // then throw an exception.
        throw Exception('Failed to load Products');
      }
      
    }

Upvotes: 0

Related Questions