Home > Mobile >  how to decode json from server in dart?
how to decode json from server in dart?

Time:10-17

I want to decode a json which is coming back from server when the statuscode was 200 and initialize them to a variable, but i don't know how to do that.

here is my request codes to server:

_SendInquiryReq({
    required BuildContext context,
  }) async {
    final prefs = await SharedPreferences.getInstance();
    var tok = prefs.getString('tok');

    var Num = NumberController.text;

    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'Authorization': 'Bearer $tok',
      'Cookie':
          '.AspNetCore.Session = some thing'
    };

    var request = http.MultipartRequest(
        'GET', Uri.parse('my Link/$Num'));

    request.headers.addAll(headers);

    http.StreamedResponse response = await request.send();

    if (response.statusCode == 200) {
      print(await response.stream.bytesToString());
      print("Ok");
    } else {
      print(response.reasonPhrase);
    }
  }

CodePudding user response:

You need to make a class that map your JSON to Class Instance like this:

class IdModel {
  String id;

  IdModel({this.id});

  IdModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    return data;
  }
}

Now Whenever you are getting the raw JSON response just use the class like this :

IdModel model = IdModel.fromJson(yourJson);

Use the model to get an id!

CodePudding user response:

  • First, you have to wait for a response to finish receiving by using await
  • Proceed with jsonDecode or json.decode method to decode into map
  • You can access your data like decodedMap['id']

final headers = {'key': 'value'}; final request = http.MultipartRequest('POST', Uri.parse('uri')); request.headers.addAll(headers); final response = await request.send(); final reponseString = await response.stream.bytesToString(); final decodeMap = json.decode(reponseString);

  • Related