How to convert file object to encodable json object in flutter? - json

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.

Related

nhandled Exception: NoSuchMethodError: Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'call'

I am facing an issue when data is fetched from the api and is not mapped into the model and the following error is thrown I have also posted the BodyModel class which contains the fromJson function:
Future<BodyModel> fetchJson(http.Client client, String? id) async {
final response = await client.get(
Uri.parse(uri2),
);
if (response.statusCode == 200) {
String jsonData = response.body;
print(response.body);
//print(jsonEncode(response.body));
BodyModel alpha = responseJSON(jsonData);
//print(alpha.toSet());
//bravo = alpha;
return alpha;
} else {
throw Exception('We were not able to successfully download the json data.');
}
}
BodyModel responseJSON(String response) {
final parse = jsonDecode(response);
print(parse.toString());
final resp = parse<BodyModel>((json) => BodyModel.fromJson(json));
print(resp);
return resp;
}
import 'package:flutter/material.dart';
class BodyModel {
String body;
String title;
BodyModel({
required this.body,
required this.title,
});
factory BodyModel.fromJson(Map<String, dynamic> jsonData) {
return BodyModel(
body: jsonData['body'].toString(),
title: jsonData['title'].toString(),
);
}
}
You are calling parse<BodyModel>(...).
It's not clear what you think that's supposed to do, but parse is a variable containing a Map<String, dynamic>, not a generic function.
It has type dynamic, so you won't get any warnings when misusing it.
Consider declaring parse as
Map<String, dynamic> parse = jsonDecode(response);
so it has the correct type.
From the return type of responseJSON, my guess is that you want to do:
final resp = BodyModel.fromJson(parse);

Flutter send json body in Http GET Method

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>

Converting object to an encodable object failed: Instance of 'Offset'

I'm trying to send Dart Offset points by encoding it to Json format using 'dart:convert' library.
I have gone through the documentation https://api.flutter.dev/flutter/dart-convert/jsonEncode.html.
The error I'm getting is for serializing the inbuilt classes.
The following JsonUnsupportedObjectError was thrown while handling a gesture:
Converting object to an encodable object failed: Instance of 'Offset'
How can i serialize inbuilt class like Offset and Paint class, is this the correct way to send the data to server?
TestData class contains Offset point and toJson() function
class TestData {
TestData(this.point);
Offset point;
toJson() {
return{
'point': point,
};
}
}
Encoder function
String jsonEncoder() {
Map testDataMap = this.testDataObj.toJson();
String jsonStringData = jsonEncode(testDataMap);
return jsonStringData;
}
I would return the JSON explicitly:
return { 'point': {dx: "$point.dx", dy: "$point.dy"}, };

Is there some error in parsing object using swifty json?

I'm trying to parse json to an object but i get this error?
Here's the function:
private func unwrap(_ object: Any) -> Any {
switch object {
case let json as JSON:
return unwrap(json.object)
case let array as [Any]:
return array.map(unwrap)
case let dictionary as [String: Any]:
var unwrappedDic = dictionary
for (k, v) in dictionary {
unwrappedDic[k] = unwrap(v)
}
return unwrappedDic
default:
return object
}
}
but I'm getting this error:
EXC_BAD_ACCESS (code=2, address=0x16f9cbfe0)

"Unexpected Character" on Decoding JSON

The following is the code:
static TodoState fromJson(json) {
JsonCodec codec = new JsonCodec();
List<Todo> data = codec.decode(json["todos"]);
VisibilityFilter filter = codec.decode(json['visibilityFilter']);
return new TodoState(todos: data,
visibilityFilter: filter);
}
Error produced by Android Studio:
[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
FormatException: Unexpected character (at character 3)
Any idea how to make it work?
This is the output of the Json as produced by Redux.
There's a problem with your code as well as the string you're trying to parse. I'd try to figure out where that string is being generated, or if you're doing it yourself post that code as well.
Valid Json uses "" around names, and "" around strings. Your string uses nothing around names and '' around strings.
If you paste this into DartPad, the first will error out while the second will succeed:
import 'dart:convert';
void main() {
JsonCodec codec = new JsonCodec();
try{
var decoded = codec.decode("[{id:1, text:'fdsf', completed: false},{id:2, text:'qwer', completed: true}]");
print("Decoded 1: $decoded");
} catch(e) {
print("Error: $e");
}
try{
var decoded = codec.decode("""[{"id":1, "text":"fdsf", "completed": false},{"id":2, "text":"qwer", "completed": true}]""");
print("Decoded 2: $decoded");
} catch(e) {
print("Error: $e");
}
}
The issue with your code is that you expect the decoder to decode directly to a List. It will not do this; it will decode to a dynamic which happens to be a List<dynamic> whose items happen to be Map<String, dynamic>.
See flutter's Json documentation for information on how to handle json in Dart.
I don't know if that's the case, but I got a similar error when me JSON looks like this
[
{
...
},
]
and not like this
[
{
...
}
]
The comma was causing the issue.
If Anyone came here and your are using dio package to call http request you need to set responseType to plain
BaseOptions options = new BaseOptions(
baseUrl: "<URL>",
responseType: ResponseType.plain
);
I also have similar type of error, Be make sure that the argument of .decode method shouldn't be empty object.
try {
if(json["todos"].isNotEmpty) {
List<Todo> data = codec.decode(json["todos"]);
}
if(json["todos"].isNotEmpty) {
VisibilityFilter filter = codec.decode(json['visibilityFilter']);
}
}
catch(e) {
print(e);
}
Do try this, hope it will work for you.