0
votes

I'm trying to get parse json data from REST API in node.js with express and mongodb and then display it like userdata. The problem is no matter what I tried it won't parse the data it will either throw and exception like Unhandled Exception: NoSuchMethodError: Class '_InternalLinkedHashMap' has no instance method 'cast' with matching arguments. Or it just displays null. I am trying to parse this json data: {"userData":{"_id":"5d3c29fdb1b0fd22182ae683","personName":"Damian","userIdentificationEMAIL":"[email protected]","dateofbirth":"14.07.2000","grad":"Los Angeles","postanskibroj":"2B","ulica":"Jackovina","drzava":"California","faiID":"123456789","nacionalniID":"000"},"request":{"type":"GET","url":"http://localhost:3000/products"}} the request field in the json data isn't actually needed for anything I just don't know If I should leave it out or not...someone commented that it's falsely refrenced. Also I can put the whole userData in an array when it get's fetched from the API If that helps.

I have tried quicktype but to no avail, I've tried many examples and ways from stack and generally from the net but I'm getting no where.

I'm managing to get the data from the API but failing short to actually get it parsed and then use it to display the user it's data.

// To parse this JSON data, do
//
//     final userData = userDataFromJson(jsonString);

import 'dart:convert';

UserData userDataFromJson(String str) => UserData.fromJson(json.decode(str));

String userDataToJson(UserData data) => json.encode(data.toJson());

class UserData {
    List<UserDatum> userData;
    Request request;

    UserData({
        this.userData,
        this.request,
    });

    factory UserData.fromJson(Map<String, dynamic> json) => new UserData(
        userData: new List<UserDatum>.from(json["userData"].map((x) => UserDatum.fromJson(x))),
        request: Request.fromJson(json["request"]),
    );

    Map<String, dynamic> toJson() => {
        "userData": new List<dynamic>.from(userData.map((x) => x.toJson())),
        "request": request.toJson(),
    };
}

class Request {
    String type;
    String url;

    Request({
        this.type,
        this.url,
    });

    factory Request.fromJson(Map<String, dynamic> json) => new Request(
        type: json["type"],
        url: json["url"],
    );

    Map<String, dynamic> toJson() => {
        "type": type,
        "url": url,
    };
}

class UserDatum {
    String id;
    String personName;
    String userIdentificationEmail;
    String dateofbirth;
    String iDPhoto;
    String grad;
    String postanskibroj;
    String ulica;
    String drzava;
    String faiId;
    String nacionalniId;

    UserDatum({
        this.id,
        this.personName,
        this.userIdentificationEmail,
        this.dateofbirth,
        this.iDPhoto,
        this.grad,
        this.postanskibroj,
        this.ulica,
        this.drzava,
        this.faiId,
        this.nacionalniId,
    });

    factory UserDatum.fromJson(Map<String, dynamic> json) => new UserDatum(
        id: json["_id"],
        personName: json["personName"],
        userIdentificationEmail: json["userIdentificationEMAIL"],
        dateofbirth: json["dateofbirth"],
        iDPhoto: json["iDPhoto"],
        grad: json["grad"],
        postanskibroj: json["postanskibroj"],
        ulica: json["ulica"],
        drzava: json["drzava"],
        faiId: json["faiID"],
        nacionalniId: json["nacionalniID"],
    );

    Map<String, dynamic> toJson() => {
        "_id": id,
        "personName": personName,
        "userIdentificationEMAIL": userIdentificationEmail,
        "dateofbirth": dateofbirth,
        "iDPhoto": iDPhoto,
        "grad": grad,
        "postanskibroj": postanskibroj,
        "ulica": ulica,
        "drzava": drzava,
        "faiID": faiId,
        "nacionalniID": nacionalniId,
    };
}

I just need to parse the data and display it in a List or a Text and be able to drop it in a variable and use it troughout the app. Any help is greatly appreciated. Thank You. Cheers!

2
It looks like you are expecting to get a list of users from the API, yet the example JSON you show only contains one, with no evidence of [] characters introducing a JSON array. Is there a different API call the returns several users? If there's only one, your code can be simplified a bit as it doesn't need to try to build a list.Richard Heap
@RicharHeap I added braces [] to the api request and now it looks like this {"userData":[{"_id":"5d3c29fdb1b0fd22182ae683","personName":"Damian","userIdentificationEMAIL":"[email protected]","dateofbirth":"14.07.2000","iDPhoto":"uploads\\1564223997727wraith.jpg","grad":"Los Angeles","postanskibroj":"2B","ulica":"Jackovina","drzava":"California","faiID":"123456789","nacionalniID":"000"}]} but yeah I'm actually trying to fetch just user data for a specific user so I only get one userMichael Knight

2 Answers

0
votes

You have syntax error in your json data.

I checked it on the data you posted with the question.

Try to generate dart code for your classes by visiting here

you will get an Autogenerated Class first then sub classes.

EDIT



You can rename Autogenerated class but make sure you change it in the below method as well

then pass your json data do function like mentioned below

fetchData() async{
  Response response;
  response = await get("yourURL");
  var json = jsonDecode(response.body);
  List<Autogenerated> _userDataList = Autogenerated.fromJson(json); 
}
0
votes

With your change to the JSON text to contain a JSON array, your code should work.

It would be more elegant to change the factory constructor as follows:

  factory UserData.fromJson(Map<String, dynamic> json) => UserData(
        userData: json["userData"]
            .map<UserDatum>((x) => UserDatum.fromJson(x))
            .toList(),
        request: Request.fromJson(json["request"]),
      );

Access fields like this:

  print(UserData.fromJson(decode).userData[0].dateofbirth);