Eugene
Eugene

Reputation: 1125

Dart unable to parse JSON from string to int

I am trying to parse a JSON value from string to int but got stuck :( The code below shows a HTTP get request and retrieving a JSON object in which I want to obtain the 'reps' value in Integer.

var response = await httpClient.get(url, headers: {
          'Content-type': 'application/json',
          'Accept': 'application/json',
          'X-API-Key': apikey
        });
        print('Response status: ${response.statusCode}');
        print('Response body: ${response.body}');
        var res = json.decode(response.body);
        String repStr = res['reps'];
        print(repStr);
        int repInt = int.parse(repStr);

The debug console shows the following error on the line

String repStr = res['reps'];

E/flutter ( 8562): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'int' is not a subtype of type 'String'

Upvotes: 0

Views: 3585

Answers (1)

As the exception explains, the value res['reps'] is already an integer you don't need to parse it.

 int repStr = res['reps'];

Upvotes: 1

Related Questions