jsonstringflutterdartjsonconvert

how to convert json string to json object in dart flutter?


I have string like this,

{id:1, name: lorem ipsum, address: dolor set amet}

And I need to convert that string to json, how I can do it in dart flutter? thank you so much for your help.


Solution

  • You have to use json.decode. It takes in a json object and let you handle the nested key value pairs. I'll write you an example

    import 'dart:convert';
    
    // actual data sent is {success: true, data:{token:'token'}}
    final response = await client.post(url, body: reqBody);
    
    // Notice how you have to call body from the response if you are using http to retrieve json
    final body = json.decode(response.body);
    
    // This is how you get success value out of the actual json
    if (body['success']) {
      //Token is nested inside data field so it goes one deeper.
      final String token = body['data']['token'];
    
      return {"success": true, "token": token};
    }