enter image description here here is the json response I get through notification while decoding the json i get an error
the method I tried
var data = message.data;
Map<String, dynamic> data1 = json.decode(data);
the error I got on json.decode(data);
The argument type 'Map<String, dynamic>' can't be assigned to the parameter type 'String'
Related
I have developed some kind of modules to ease up converting json data into models. This usually already works well. I can convert various type of maps and lists without problems.
At the moment I faced a weird case. I know that the incoming data is List<String>, as this is a list of email addresses. But of course in its raw format, it's currently List<dynamic>.
These are my attempts to convert. First:
var data = json["emails"]; // works
var list = data as List; // works
var listStr = list as List<String>; // error
Error message: type 'List<dynamic>' is not a subtype of type 'List<String>' in type cast
Second:
var data = json["emails"]; // works
var list = data as List; // works
List<String> listStr = list; // error
Error message: type 'List<dynamic>' is not a subtype of type 'List<String>' in type cast
Third:
var data = json["emails"]; // works
var list = data as List; // works
List<String> listStr = list.map((e) {
print(e.runtimeType); // result: String
return e;
}).toList(); // error
Error message: type 'List<dynamic>' is not a subtype of type 'List<String>'
Fourth:
var data = json["emails"]; // works
var list = data as List; // works
List<String> listStr = list.map((e) {
print(e.runtimeType); // result: String
print(e.toString().runtimeType); // result: String
return e.toString();
}).toList(); // success
Fifth:
var data = json["emails"]; // works
var list = data as List; // works
List<String> listStr = [for (var email in list) email]; // success
Why is this happening? How can I resolve this without adding .toString(), because I may have other cases in the future where I might not be converting from json, and the list might not be a simple String object. I just don't understand why, with data type already String, it's not assignable or convertible from dynamic, even though I already use map().toList(). The fifth method works at least. But it's still strange.
i tried many solutions but it still give me the same error :
"Unhandled Exception: type '_InternalLinkedHashMap<dynamic, dynamic>' is not a subtype of type 'Map<String, dynamic>?'"
Future<GetCustomerList> _getStateList() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
var token = prefs.getString("userToken");
final String url = "http://194.195.245.189:8069/get_partners?params: {}";
Map<dynamic, dynamic> qParams = {
"params": {}
};
Map<String, String> headers = {'Cookie':'session_id=$token',
'Content-Type':'application/json; charset=UTF-8'};
var customerList = await http.get(Uri.parse(url),headers: headers,body: qParams);
if (customerList.statusCode == 200) {
return GetCustomerList.fromJson(json.decode(customerList.body));
} else {
throw Exception('Failed to load Customers');
}
}
you have to convert your result into a map take inspiration from this link
Unhandled Exception: InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>
Im trying to map profilePicture to a File object using dart , i have the profilePicture saved as IFormFile in the c# backend..
This is the mapping function and other functions in my ManageUserModel class:
Map<String, dynamic>toMap() {
return {
"profilePicture":profilePicture,
(other mappings)
}
}
List<ManageUserModel> fromJson(String jsonData) {
// Decode json to extract a map
final data = json.decode(jsonData);
return List<ManageUserModel>.from(
data.map((item) => ManageUserModel.fromJson(item)));
}
String toJson(ManageUserModel data) {
// First we convert the object to a map
final jsonData = data.toMap();
// Then we encode the map as a JSON string
return json.encode(jsonData);
}
Note that profilePicture is one of the ManageUserModel attributes and is of type File .
When the http update request is invoked via this method:
Future<String> updateUser(ManageUserModel data) async {
final response = await client.put("$baseUrl/Users",
headers: {"content-type": "application/json"},
body: toJson(data),
);
if (response.statusCode == 200) {
return "Success";
} else {
return "Fail";
}
}
i get this error:
E/flutter (10061): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Converting object to an encodable object failed: Instance of '_File'
Any help ?
From the error you've provided, it looks like you're trying to map '_File' object as a json.
E/flutter (10061): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Converting object to an encodable object failed: Instance of '_File'
That won't do since fromJson can only handle Maps. What you may want to consider is to store the file as an image URL, or as what have been previously mentioned in the comments - as base64.
Im using Dart "json_serializable" package to deserialize below Firestore data structure in Flutter application.
{
googleBookId: jjl4BgAAQBAJ,
providers: [
{providerId: 2FA9fULKLLf7VUPPFnFRnv},
{providerId: 8UYTGUHY7UJS432FVBJRnv}
]
}
And below is the Model class to map:
#JsonSerializable()
class Book {
String googleBookId;
List<Provider> providers;
Book(this.googleBookId,
{List<Provider> providers})
: providers = providers ?? <Provider>[];
factory Book.fromJson(Map<String, dynamic> map) => _$BookFromJson(map);
Map<String, dynamic> toJson() => _$BookToJson(this);
}
#JsonSerializable()
class Provider {
String providerId;
Provider(this.providerId);
factory Provider.fromJson(Map<String, dynamic> map) => _$ProviderFromJson(map);
Map<String, dynamic> toJson() => _$ProviderToJson(this);
}
While deserializing I'm getting following error
_CastError (type '_InternalLinkedHashMap' is not a subtype of type 'Map' in type cast)
Is there any other library that I can use to deserialize document?
As posted in other question I was able to deserializing Firestore document by encode in to JSON string and back to JSON object before deserialization.
#Chiziaruhoma Ogbonda thanks for clarification, it helps me to think in other way rather directly tying to deserialize document.
The solution is to use the anyMap and explicitToJson properties.
#JsonSerializable(explicitToJson: true, anyMap: true)
class Book {
}
Okay so i don't know if you know but then firestore sends you a Map not JSON. You're trying to use JSON Serializer.
JSON is
Map<String,dynamic>
while firestore sends
Map<dynamic,dynamic>. So you can't use parse it as json.
Check this out https://medium.com/#atul.sharma_94062/how-to-use-cloud-firestore-with-flutter-e6f9e8821b27
I'm requesting a JSON object with Alamofire and accessing it with SwiftyJSON.
The response of my request is this :
// JSON webservice ...
[
{
"message":"Please connect"
}
]
As you can see I need to remove the string "// JSON webservice ..." because it is actually not a valid JSON object.
Note that I'm using the .responseString otherwise I could not remove the string part.
So in order to remove the string I'm doing :
let jsonString = data?.stringByReplacingOccurrencesOfString("// JSON webservice ...", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
Now I'm with my String I can do :
var json = SwiftyJSON.JSON(jsonString!)
and I can print the json :
println(json)
BUT whatever I print a value
println(json[0]["message"].string)
is nil.
I finally found myself a solution :
We get our string (data) from the .responseString method
We remove the part that cause the fail of the serialization of the JSON object
We convert our string to NSData and try to serialize our JSON object :
let data = jsonString?.dataUsingEncoding(NSUTF8StringEncoding)
let jsonData = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray?
Now it should be fine and everything is working when trying to print a value of the JSON object
var json = SwiftyJSON.JSON(jsonData!)
println(json[0]["message"])
It prints the right value.