I have following model class.
#JsonSerializable()
class Login {
String? userName;
String? password;
Login({required this.userName, required this.password});
factory Login.fromJson(Map<String, dynamic> json) => _$LoginFromJson(json);
Map<String, dynamic> toJson() => _$LoginToJson(this);
}
Generated part file.
Login _$LoginFromJson(Map<String, dynamic> json) => Login(
userName: json['userName'] as String?,
password: json['password'] as String?,
);
Map<String, dynamic> _$LoginToJson(Login instance) => <String, dynamic>{
'userName': instance.userName,
'password': instance.password,
};
when i try to use it to post to api with follow code
Future<void> loginUser(Login login) async => {
print(login.toJson().toString());
}
Result from the print statement (cause convertion error)
{userName: test, password: password}
Expecting valid json to post is
{
"username": "string",
"password": "string"
}
Error Message
Error: DioError [DioErrorType.other]: Converting object to an encodable object failed: Instance of '_HashSet<String>'
Remove the => from
Future<void> loginUser(Login login) async => {
print(login.toJson().toString());
}
to
Future<void> loginUser(Login login) async {
print(login.toJson().toString());
}
In the first example, it is an arrow function where the brackets { } stand for a set literal since it's right after the arrow, much like in the generated _$LoginToJson function but without describing the types of the set.
In the second example, it is a normal function the brackets { } define the body of the function.
You might be looking to call jsonEncode (import dart:convert;) which takes a value, such as a Map<String, dynamic> and turns it into a String in json format.
Update the print statement as follows:
print(jsonEncode(login.toJson()));
While the generated functions parse the object to a format that is suitable for JSON, it doesn't turn it into an actual String. You'll need to encode it with jsonEncode. Similarly, when processing a JSON response, you'll need to jsonDecode the response body to get a Map<String, dynamic> structure that you can then pass into the generated fromJson functions.
Related
I'm following this tutorial from devs docs to fetch data from internet but I can't decode response to User object.
Since I'm using Postman to check API I can tell you that my request is successfully received and server responses me with 200 and a body full of data (name, id and token) but when I try to call fromJson method inside try-catch block to create User object it fails and this error is printed :
flutter: Response 200
flutter: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
This is my User class :
class User extends Equatable {
final String token;
final String name;
final String id;
const User({
required this.token,
required this.name,
required this.id,
});
static const User empty = User(token: "token", name: "name", id: "id");
Map<String, dynamic> toMap() {
return <String, String>{
'token': token,
'name': name,
'id': id,
};
}
factory User.fromMap(Map<String, dynamic> json) {
return User(
token: json['token'] ?? "token",
name: json['name'] ?? "name",
id: json['id'] ?? "id",
);
}
String toJson() => json.encode(toMap());
factory User.fromJson(Map<String, dynamic> jsonMap) => User.fromMap(jsonMap);
#override
String toString() {
return token + ' ' + name + ' ' + id + '\n';
}
#override
List<Object?> get props => [token, name, id];
}
UserCredentials that's just a wrapper for username and password :
class UserCredentials {
final String name;
final String email;
final String password;
UserCredentials(
{required this.name, required this.email, required this.password});
factory UserCredentials.fromJson(Map<String, dynamic> json) {
return UserCredentials(
name: json['name'] as String,
email: json['email'] as String,
password: json['password'] as String,
);
}
Map<String, String> toJsonRegistration() {
return {
"name": name,
"email": email,
"password": password,
};
}
Map<String, String> toJsonLogin() {
return {
"email": email,
"password": password,
};
}
#override
String toString() {
return name + " " + email + " " + password + '\n';
}
}
And this is my user_repository function used to get data from server :
Future<User> _login(UserCredentials user) async {
User? userFetched;
//print(user);
http.Response response = await http.post(
Uri.parse("http://link_to_repo"),
body: user.toJsonLogin(),
);
print("Inizio");
print((response.body));
print(jsonDecode(response.body));
print(User.fromJson(jsonDecode(response.body)));
print("fine");
if (response.statusCode == 200) {
print(response.statusCode);
try {
userFetched = User.fromJson(jsonDecode(response.body));
print(userFetched);
} catch (e) {
print(e);
}
print("End");
return userFetched!;
} else {
print("Login Failure from repository");
throw Exception("Email already taken");
}
}
As you seen above it's able to print "Response 200" but not to complete successfully the operation inside try-catch block.
Edit :
This is the response.body :
{"data" : {"token":"50|IUMNqKgc7Vffmz8elRd0MIZeSyuEgHL418KwQ0Jz","name":"test","id":1}}
And jsonDecode(response.body)) :
{data: {token: 50|IUMNqKgc7Vffmz8elRd0MIZeSyuEgHL418KwQ0Jz, name: test, id: 1}}
Solution :
This post is a little confusing but to be clear :
Clucera gave me the exact solution to fetch the data and create User object so I accepted its answers.
Josip Domazet's answer helped me fixing the error but he didn't solve the problem because I still couldn't create User data.
Looking at your code it looks like you are doing the following
User.fromJson(jsonDecode(response.body));
and from there you are creating the User instance with the following factory
factory User.fromMap(Map<String, dynamic> json) {
return User(
token: json['token'] ?? "token",
name: json['name'] ?? "name",
id: json['id'] ?? "id",
);
The issue is that your Json is contained in another json called "data" as your print response show
{data: {token: 50|IUMNqKgc7Vffmz8elRd0MIZeSyuEgHL418KwQ0Jz, name: test, id: 1}}
in this case you have two solution, either you nest the keys inside your constructor (don't suggest you this approach)
factory User.fromMap(Map<String, dynamic> json) {
return User(
token: json['data']['token'] ?? "token",
name: json['data']['name'] ?? "name",
id: json['data']['id'] ?? "id",
);
Or where you parse the json you can extract directly the data json (I suggest you this option)
User.fromJson(jsonDecode(response.body)['data']);
jsonDecode(response.body) will return a Map. However your constructor User.fromJson takes a String as argument. Decoding it once is enough and from then on your can work with the Map you already have. So no need to call jsonDecode again in fromJson, this should work fine:
factory User.fromJson(Map<String, dynamic> jsonMap) =>
User.fromMap(jsonMap);
If we look at your exception it tell us just that:
flutter: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'String'
Your constructor expects a String but received a Map (_InternalLinkedHashMap).
When the app launch it triggers an API call and in my case, I want to store the response data for later use, so I used shared preferences for that and stored response data as a string. now I want to properly decode the data to use, from the stored string from shared preferences.
here is how I covert the data to string,
SharedPreferences prefs = await SharedPreferences.getInstance();
Response response = await _dio.post(
_baseUrl,
data: {"index": indexNum, "password": password},
options: Options(contentType: Headers.formUrlEncodedContentType),
);
if (response.statusCode == 200) {
var result = response.data;
//convert result data to string
var resultData = Result.encode(result);
// store the resultData in shared_preferences
prefs.setString('results', resultData);
}
encode method,
class Result {
Result({
required this.table,
required this.data,
});
String table;
List<Data> data;
factory Result.fromJson(Map<String, dynamic> json) => Result(
table: json["table"],
data: List<Data>.from(json["data"].map((x) => Data.fromJson(x))),
);
//encode method
static String encode(List<dynamic> results) => json.encode(
results.map((result) => result.toString()).toList(),
);
}
here is my approach to decode data from string,
getData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String? resultData = prefs.getString('results');
List<dynamic> decodedJson = jsonDecode(resultData!);
print(decodedJson);
}
resultData string,
resultData string after decode,
I am new to flutter and what I want is the proper way to decode this data from models. Below are my model classes.
import 'dart:convert';
class Result {
Result({
required this.table,
required this.data,
});
String table;
List<Data> data;
factory Result.fromJson(Map<String, dynamic> json) => Result(
table: json["table"],
data: List<Data>.from(json["data"].map((x) => Data.fromJson(x))),
);
static String encode(List<dynamic> results) => json.encode(
results.map((result) => result.toString()).toList(),
);
}
class Data {
Data({
required this.subjectName,
required this.year,
required this.credits,
required this.sOrder,
required this.result,
required this.onlineAssignmentResult,
});
String subjectName;
String year;
String credits;
String sOrder;
String result;
String onlineAssignmentResult;
factory Data.fromJson(json) => Data(
subjectName: json["subject_name"],
year: json["year"],
credits: json["credits"],
sOrder: json["s_order"],
result: json["result"],
onlineAssignmentResult: json["online_assignment_result"],
);
}
Appreciate your time and help.
Your JSON is in the wrong syntax for Flutter to decode with jsonDecode()
All strings and variable names need to be enclosed in " or '
I.e. {subject_name: should be {"subject_name":
I was wondering if anyone could help, please? I'm very new to Flutter/Dart here and I'm trying to parse a nested JSON response, into a model. I've used the "JSON to Dart" generator, which seems to have worked well, except when it is parsing "responses".
I suspect the issue is because the "responses" vary in results - sometimes it could be null, a single array, or multiple.
Running .runtimeType has shown me that it can return null if it's empty, List<dynamic> if there is only one array, and _InternalLinkedHashMap<String, dynamic> when there are multiple.
I have tried many different approaches to try and resolve this and looked through many different StackOverflow answers, but nothing seems to work. The error simply changes with every change I make.
Below is my code and my error.
The error:
_TypeError (type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f')
The code:
class VideoComments {
int id;
String comment;
int uid;
int likes;
bool isLikedByUser;
String posterProfilePic;
String posterUsername;
List<Responses> responses;
VideoComments(
{this.id,
this.comment,
this.uid,
this.likes,
this.isLikedByUser,
this.posterProfilePic,
this.posterUsername,
this.responses});
VideoComments.fromJson(Map<String, dynamic> json) {
print("RESP: ${json['responses'].runtimeType}");
id = json['id'];
comment = json['comment'];
uid = json['uid'];
likes = json['likes'];
isLikedByUser = json['isLikedByUser'];
posterProfilePic = json['poster_profile_pic'];
posterUsername = json['poster_username'];
if (json['responses'] != null) {
List<Responses> responses = [];
json['responses'].forEach((v) {
responses.add(new Responses.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['comment'] = this.comment;
data['uid'] = this.uid;
data['likes'] = this.likes;
data['isLikedByUser'] = this.isLikedByUser;
data['poster_profile_pic'] = this.posterProfilePic;
data['poster_username'] = this.posterUsername;
if (this.responses != null) {
data['responses'] = this.responses.map((v) => v.toJson()).toList();
}
return data;
}
}
class Responses {
int id;
String comment;
int uid;
int likes;
bool isLikedByUser;
Responses({this.id, this.comment, this.uid, this.likes, this.isLikedByUser});
Responses.fromJson(Map<String, dynamic> json) {
id = json['id'];
comment = json['comment'];
uid = json['uid'];
likes = json['likes'];
isLikedByUser = json['isLikedByUser'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['comment'] = this.comment;
data['uid'] = this.uid;
data['likes'] = this.likes;
data['isLikedByUser'] = this.isLikedByUser;
return data;
}
}
Any help is appreciated!
Just for the fun of it - I tried to implement the same thing using json_serializable since I recommended it in my comment. Hopefully this shows you that it is not that complicated - in fact, it is simpler than actually figuring out how to code it your self.
First I started with the blank Flutter project.
Second, I added required dependencies to pubspec.yaml:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
# Added this
json_annotation: ^4.0.1
dev_dependencies:
flutter_test:
sdk: flutter
# and these two...
build_runner: ^2.0.4
json_serializable: ^4.1.3
Next thing, I created a separate file json_demo.dart, and took part of your code. I also added few things:
part instruction that will include generated json mapping file
For each class added .fromJson named constructor
For each class added toJson() method.
Added #JsonSerializable() for each class - this is how the tool knows which class to look at
Added #JsonKey(name: 'poster_profile_pic') and #JsonKey(name: 'poster_username') - since your filed names are different than Json property names (poster_profile_pic vs posterProfilePic), you need to tell the tool how to rename it back and forth.
Made all properties nullable (since I'm using latest version with null-safety)
import 'package:json_annotation/json_annotation.dart';
part 'json_demo.g.dart';
#JsonSerializable()
class VideoComments {
int? id;
String? comment;
int? uid;
int? likes;
bool? isLikedByUser;
#JsonKey(name: 'poster_profile_pic')
String? posterProfilePic;
#JsonKey(name: 'poster_username')
String? posterUsername;
List<Responses>? responses;
VideoComments(
{this.id,
this.comment,
this.uid,
this.likes,
this.isLikedByUser,
this.posterProfilePic,
this.posterUsername,
this.responses});
factory VideoComments.fromJson(Map<String, dynamic> json) => _$VideoCommentsFromJson(json);
Map<String, dynamic> toJson() => _$VideoCommentsToJson(this);
}
#JsonSerializable()
class Responses {
int? id;
String? comment;
int? uid;
int? likes;
bool? isLikedByUser;
Responses({this.id, this.comment, this.uid, this.likes, this.isLikedByUser});
factory Responses.fromJson(Map<String, dynamic> json) => _$ResponsesFromJson(json);
Map<String, dynamic> toJson() => _$ResponsesToJson(this);
}
Now, simply run flutter pub run build_runner build, and you get json_demo.g.dart file generated:
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'json_demo.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
VideoComments _$VideoCommentsFromJson(Map<String, dynamic> json) {
return VideoComments(
id: json['id'] as int?,
comment: json['comment'] as String?,
uid: json['uid'] as int?,
likes: json['likes'] as int?,
isLikedByUser: json['isLikedByUser'] as bool?,
posterProfilePic: json['poster_profile_pic'] as String?,
posterUsername: json['poster_username'] as String?,
responses: (json['responses'] as List<dynamic>?)
?.map((e) => Responses.fromJson(e as Map<String, dynamic>))
.toList(),
);
}
Map<String, dynamic> _$VideoCommentsToJson(VideoComments instance) =>
<String, dynamic>{
'id': instance.id,
'comment': instance.comment,
'uid': instance.uid,
'likes': instance.likes,
'isLikedByUser': instance.isLikedByUser,
'poster_profile_pic': instance.posterProfilePic,
'poster_username': instance.posterUsername,
'responses': instance.responses,
};
Responses _$ResponsesFromJson(Map<String, dynamic> json) {
return Responses(
id: json['id'] as int?,
comment: json['comment'] as String?,
uid: json['uid'] as int?,
likes: json['likes'] as int?,
isLikedByUser: json['isLikedByUser'] as bool?,
);
}
Map<String, dynamic> _$ResponsesToJson(Responses instance) => <String, dynamic>{
'id': instance.id,
'comment': instance.comment,
'uid': instance.uid,
'likes': instance.likes,
'isLikedByUser': instance.isLikedByUser,
};
Note how it correctly renamed the json property based on the annotation:
posterProfilePic: json['poster_profile_pic'] as String?,
One more thing to notice - this is how it fixed the problem you had:
responses: (json['responses'] as List<dynamic>?)
?.map((e) => Responses.fromJson(e as Map<String, dynamic>))
.toList(),
From now on, each time you change your class, simple re-run the build script.
As you explore further, you'll see that it can handle enums, it has nice annotations to automatically rename all fields in a class from snake case to kebab case (or whatever it is called). But most importantly - does it in a consistent and tested way. As you add more classes, it will really help you save some time...
And to make your life easier, create user snippet in VS Code (File->Preferences->User snippets):
{
"Json Serializible": {
"prefix": "serial",
"body": [
"factory ${1}.fromJson(Map<String, dynamic> json) => _$${1}FromJson(json);",
"Map<String, dynamic> toJson() => _$${1}ToJson(this);"
]
}
}
Here's how to use it:
Copy the name of your class
start typing 'serial' - this is the shortcut for the code snippet
Select the snippet and paste the class name - it will paste it 3 times where needed.
See - simpler than learning how to manually encode/decode Json....
As #Andrija suggested, that is certainly a good way, if you don't want to use that then go ahead with the vscode extension bendixma.dart-data-class-generator, create your class and keep your variables, just do ctrl + shift + p -> Search data class, hit enter when you find dart data class generator from class properties.
Thank you everyone for your responses. I have no resolved the issue.
I have changed my code (in respect to the issue area) to the following:
if (json['responses'].length > 0) {
json['responses'].forEach((e) => responses.add(Responses.fromJson(e)));
} else if (json['responses'].length == 0 || json['responses'] == null) {
responses = null;
}
and on my web server, I have wrapped the "responses" in another (parent) array.
it is an error related to data type. Please cross the the JSON response and Dart class variable data type. String variable can't be an Int or Double value. Or do one thing change all variable into Dynamic type.
But yes it is not good practice to have dynamic as datatype for all variable.
I have a response
[{details: {macId:789101112}}]
jsonData['details'] will return String {macId:789101112}
Parsing code :
fromJson(Map<String, dynamic> jsonData) => User(
details: UserDetails.fromJson(jsonData['details'] as Map<String, dynamic>),
);
class UserDetails{
final String macId;
UserDetails({this.macId});
static UserDetails fromJson(Map<String, dynamic> json) =>
UserDetails(macId: json['macId'] as String);
}
Try looking at the original source. From your description, it sounds like it looks something like:
[{"details": "{\"macId\": 789101112}"}]
That is, the value of the "details" entry is a string containing JSON source code.
You will need to parse that a second time:
fromJson(Map<String, dynamic> jsonData) =>
User(details: UserDetails.fromJson(jsonDecode(jsonData['details'])));
The reason for this is likely that the place where the you generate JSON data from UserDetails object, it calls jsonEncode on the map, and it should not do that. Just let the UserDetails-to-JSON function return a map, so that that map can be embedded in the larger JSON-like data structure. Then you won't need the second jsonDecode either.
I am trying to parse data from a Rest API inside a Dart/Flutter application. The JSON contains a field called data at the root, which contains a list of Words. I want to get a List<Word> from this JSON. I already have the following code:
Map<String, dynamic> jsonMap = json.decode(jsonString);
List<Word> temp = jsonMap['data']
.map((map) => map as Map<String, dynamic>)
.map((Map<String, dynamic> map) => Word.fromJson(map)).toList(); // map to List<Word>
Word.fromJson has the following signature:
Word.fromJson(Map<String, dynamic> json)
The final call to map gives the following error:
type 'List<dynamic>' is not a subtype of type 'List<Map<String, dynamic>>'
From my understanding, the call to map((map) => map as Map<String, dynamic>) should convert the List<dynamic> to a List<Map<String, dynamic>>, so I am confused as to why I get the error.
Any advice appreciated.
If data is a List of words, you can "cast" to generic List and iterate each item to cast into a new Word object,
List<Word> temp = (jsonMap['data'] as List).map((itemWord) => Word.fromJson(itemWord)).toList();
The key is String, and data is Dynamic, if jsonMap['data'] is a List on jsonString, it's not a Map<String,dynamic> and can not cast direct to map.
Sample of jsonString and convert:
final jsonString = '''
{
"field": "titulo",
"data": [{"teste":1},{"teste":2},{"teste":3},{"teste":4}]
}
''';
final jsonMap = json.decode(jsonString);
List<Word> temp = (jsonMap['data'] as List)
.map((itemWord) => Word.fromJson(itemWord))
.toList();
Word Class
class Word {
int teste;
Word({this.teste});
Word.fromJson(Map<String, dynamic> json) {
teste = json['teste'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['teste'] = this.teste;
return data;
}
}
Generated classs using JSON to Dart
https://javiercbk.github.io/json_to_dart/
If you want to convert a List<dynamic> to List<Map<String, dynamic>> as the title suggests, you should cast 2 times:
(jsonDecode(response.body)["data"] as List).map((e) => e as Map<String, dynamic>)?.toList();
If you are using strong mode I had to explicitly define the field type the ? was also not necessary.
Note the 'dynamic e'
(jsonDecode(response.body)["data"] as List).map((dynamic e) => e as Map<String, dynamic>).toList();