Home > other >  Can't decode JSON "_TypeError (type 'String' is not a subtype of type 'int&
Can't decode JSON "_TypeError (type 'String' is not a subtype of type 'int&

Time:08-20

I tried every solution on StackOverflow but couldn't find any answers. I'm getting API calls and then trying to decode them to use in my app. However, I couldn't find a way to do that. It gives me an error every time!

The response I get from API

{success: true, error: null, data: {id: zP********P, name: FTBContinuum, address: FTBContinuum.exaroton.me, motd: cidqu sunucusuna ho geldin!, status: 0, host: null, port: null, players: {max: 20, count: 0, list: []}, software: {id: RUg3PF9qeRywv4Z2, name: FTB Continuum, version: 1.7.0}, shared: false}}

Here is my code:

  girisFonksiyonu() async {
    var krediF = await sunucu.accountInfo('credits');
    var sunucu31 = await sunucu.servers('z*******P');
    print(sunucu31);
    var continuum = jsonEncode(sunucu31);
    var decodedJSON = jsonDecode(continuum);
    var sunucuIDF = decodedJSON['data']['id'];
    var sunucuismiF = decodedJSON['data']['name'];
    var sunucumotdF = decodedJSON['data']['motd'];
    var durumF = decodedJSON['data']['status'].toString();
    var girislikisiF = decodedJSON['data']['players']['count'].toString();

servers function:

  Future<String> servers(String serverId) async {
    var endpoint = 'servers/$serverId/';
    var notParsedJSON = await postSystem(endpoint);
    var decodedJSON = jsonDecode(notParsedJSON);
    var info = decodedJSON;
    return info.toString();
  }

postSystem function:

  Future<String> postSystem(String endpoint) async {
    var postUrl = '${env.baseUrl}/${endpoint}';

    final response = await http.post(
      Uri.parse('${postUrl}'),
      headers: {
        'Authorization': 'Bearer ${API_KEY}',
        'Content-Type': 'application/json'
      },
    );
    return response.body.toString();
  }

Here is the error I got:

enter image description here

CodePudding user response:

your code seeing the decoededJSON as a List so the data here should be int index if you are using a list if you not then you need to decode your JSON in other way to get correct data type you can provide us with json data to help you more

CodePudding user response:

decodeJson can return a list from json Array or a map, if its return a list the index must be int

if return a map the index can be string

so instead of using var, try to set a return type :

Map<String,dynamic> decodedJSON = jsonDecode(continuum);
var sunucuIDF = decodedJSON['data']['id'];
  • Related