Can't put a json on a Map on Flutter - android

I'm trying to get the data from a json and save into a map to use the data on my app, but i cant make it work.
Here´s the json example:
[
{
"Codigo_Produto": 2025,
"Qtde": 4,
"Descricao": "SERVIÇO DE ALINHAR EIXOS",
"Codigo": 3862,
"CodOS": 3862,
"Numero_da_OS": "3862"
},
{
"Codigo_Produto": 2423,
"Qtde": 4,
"Descricao": "SERVIÇO DE CAMBAGEM TRAÇÃO/TRUCK",
"Codigo": 3862,
"CodOS": 3862,
"Numero_da_OS": "3862"
}
]
Here is how i try to access the data:
Map<dynamic, dynamic> map =
jsonDecode(response.data);
print(map);
And i get this error:
E/flutter (15734): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'String'
I have also tried making in different ways but everytime i get this error.
What is wrong with my code? Is it because the response is coming insite a array? What is the best way to receive and make this data usable for my app?
The full code on the button that calls the api is here:
onPressed: () async {
Response response;
Dio dio = new Dio();
String url =
'http://192.168.15.2:8090/api/getOs';
response = await dio.post(url, data: {
"numeroos": _numeroOsController.text
});
print(response.statusCode);
print(response.data);
Navigator.pop(context, true);
},

Your response.data returns list. Check first line of your json, it has list brackets like this [.
You should retrieve your data this way:
final listOfObjects = <String,dynamic>[];
for(var obj in response.data)
{
listOfObjects.add(jsonDecode(obj));
}
return listOfObjects;
You need to change return type of your Future also, to list of your objects.

Using the json.decode you can extract the data directly to map
String responseBody = await rootBundle.loadString("assets/data.json");
var maplist = await json.decode(responseBody).cast<Map<String, dynamic>>();

Related

Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'OriginDestination' in type cast int flutter

I am trying to fetch data from a local json file in my assets. I received and decoded data and then tried to store it in a list for further use. But it give me the exception. I want the list to be of type OriginDestination, store it in database and then use it further. Can someone please tell me how can I parse data from json to OriginDestination.
Class OriginDestination -
OriginDestination cityDtoFromJson(String str) => OriginDestination.fromJson(json.decode(str));
String cityDtoToJson(OriginDestination data) => json.encode(data.toJson());
#HiveType(typeId: 0)
// ignore: non_constant_identifier_names
class OriginDestination extends HiveObject {
#HiveField(0)
City? origin;
#HiveField(1)
List<City>? destinations;
OriginDestination({
this.origin,
this.destinations,
});
factory OriginDestination.fromJson(Map<String, dynamic> json) => OriginDestination(
origin: City.fromJson(json["origin"]),
destinations: List<City>.from(
json["destinations"].map((x) => City.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"origin": origin,
"destinations": destinations,
};
Code where I am fetching data and want to use it (originDestinations is also a list of type OriginDestination) -
List<OriginDestination>? localOriginDestination = [];
Future<void> readJson() async {
final String response = await rootBundle.loadString('assets/files/node.json');
final data = await json.decode(response);
localOriginDestination = await data["data"].cast<OriginDestination>();
print(localOriginDestination);
if(localOriginDestination!=null) {
await _localStorageService.getBox().clear();
await _localStorageService.getBox().addAll(localOriginDestination!.toList());
originDestinations = _localStorageService.getOriginDestinations();
}
}
I have never used Hive before but this line of code seems suspicious to me:
localOriginDestination = await data["data"].cast<OriginDestination>();
I think you want to do something along the lines of:
localOriginDestination = [
for (final element in await data['data']) OriginDestination.fromJson(element),
];
But I can't be entirely certain without knowing what the value of await data['data'] is.
Edit, adding some more information.
The .cast method on List is only meant to be used with a type that is a subtype of the original list type, like in this example:
void main() {
List<num> nums = [1, 2, 3];
List<int> ints = nums.cast<int>();
ints.add(4);
print(ints);
}
What you are doing is essentially the same thing as this.
void main() {
List<Map<String, int>> items = [
{'A': 1, 'B': 2},
{'A': 3, 'B': 4},
];
final result = items.cast<ABC>();
print(result);
}
class ABC {
int a;
int b;
ABC.fromJson(Map<String, dynamic> json)
: a = json['A'],
b = json['B'];
}
The problem here is that the ABC class is not a subtype of Map<String, int>. Classes are not maps in the dart programming language. You need to need to call the .fromJson constructor on each element of the items list in order to get a List<ABC>.
You can do it in a few different ways.
Using map method is one approach. (you need to be on dart 2.15+ for this exact syntax)
List<ABC> result = items.map(ABC.fromJson).toList();
Looping over items with a collection for is another approach.
List<ABC> result = [for (final element in items) ABC.fromJson(element)];
Looping over items with a conventional for loop is yet another approach.
List<ABC> result = [];
for (final element in items) {
result.add(ABC.fromJson(element));
}

"The getter 'body' isn't defined for the type 'Response<dynamic>". on Flutter

i'm having a problem to put a response json on a List.
When i try to transform the body data (where the data comes) i get the error:
The getter 'body' isn't defined for the type 'Response<dynamic>'.
Try importing the library that defines 'body', correcting the name to the name of an existing getter, or defining a getter or field named 'body'.dartundefined_getter
My code is:
onPressed: () async {
Response response;
Dio dio = new Dio();
String url =
'http://192.168.15.5:8090/api/getOs';
response = await dio.post(url, data: {
"numeroos": _numeroOsController.text
});
final extractedData = json.decode(response.body) //Here is the error
as Map<String, dynamic>;
final List<ProdutoOs> loadedProducts = [];
extractedData.forEach((key, value) {
loadedProducts.add(ProdutoOs(
cod_produto: value['Codigo_Produto'],
qtd: value['Qtde'],
desc: value['Descricao'],
numOs: value['Numero_da_OS'],
codOs: value['CodOS']));
Navigator.pop(context, true);
});
}
So i'm trying to put the response.body in a List but i cant, what am i doing wrong?
I have also tried using response.data and dont get the same error, the app runs but i get:
E/flutter (11379): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'String'
Maybe try this:
List responseElements = jsonDecode(response.body);
responseElements.map((singleJsonObject) => {
// do your parsing here
});
Add the await keyword when you're parsing the url
add await before parsing the url

Flutter - unable to parse json array

I want to fetch list of cities from rest webservice, this way:
Future<List<City>> fetchCities() async {
final response =
await http.get('https://my-url/city',
headers: {HttpHeaders.acceptHeader: "application/json"});
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return compute(parseCities, response.body);
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load cities');
}
}
Then to parse:
List<City> parseCities(String responseBody) {
final parsed = json.decode(responseBody)['data']['children'].cast<Map<String, dynamic>>();
return parsed.map<City>((json) => City.fromJson(json['data'])).toList();
}
And this is City class definition:
class City {
final String id;
final String name;
City({this.id, this.name});
factory City.fromJson(Map<String, dynamic> json) {
return City(
id: json['id'],
name: json['name'],
);
}
}
My example responseBody is:
[{\"id\":\"599\",\"name\":\"Bia\u0142ystok-dev\",\"location\":{\"long\":\"23.15\",\"lat\":\"53.13\"}}]
(for now, I want to ommit location and only fetch id and name). My json.decode throws exception:
type 'String' is not a subtype of type 'int' of 'index'
How to fix that? Any ideas?
The json string you have posted does not contain the keys data or children so to parse that json you would need to change your parse method to the following:
List<City> parseCities(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<City>((json) => City.fromJson(json)).toList();
}
although I think its good practice to use List.from instead of .cast
final parsed = List<Map<String, dynamic>>.from(json.decode(responseBody));

Flutter: InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments

I'm unable to find solutions from the previously available question, I have cast json string to map
Below is my API calling method.
Future<EventResponse> fetchEvent( ) async { // here i change Future type
String url='http://xxxxxxxxxxxx.tk/api/userapp/event/lists';
var headers = new Map<String, String>();//here i defined Map type
headers['Auth-Key'] = 'OCDOC#2018';
headers['End-Client'] = 'OCDOC';
var body = new Map<String, String>();//here i defined Map type
headers['schedule'] = 'present';
http.Response res = await http.post(url,headers: headers, body: body);
final parsed=json.decode(res.body);
var myMap = Map<String, dynamic>.from(parsed);
EventResponse eventResponse = EventResponse.convertEventResponse(myMap);
return eventResponse;
}
this is my convertEventResponse methode
factory EventResponse.convertEventResponse(Map<String, dynamic> json) {
List<dynamic> events = json['eventList'];
List<Event> eventList = events.map((e) => Event.convertEvent(e)).toList(); //here i changed by #Richard Heap answer
return EventResponse(
error: json['error'],
status: json['status'],
deliveryCharges: json['deliveryCharge'],
imageBaseUrl: json['image_base_url'],
imageLogoUrl: json['image_logo_url'],
eventList: eventList,
);
}
The error i'm getting.
InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments.
Use instead
.cast<String,dynamic>();
See also https://api.dartlang.org/stable/2.0.0/dart-core/Map/cast.html
Usually it's better to use Map<String,String>.from(oldMap) instead of cast<...>(...)

Json Parser error in React native

Hello I need a solution for multiple json post through react native since I'm new in React native. Here is my new json data I need to post
[
{
"rollno": "10",
"typeofattendence": 1
},
{
"rollno": "10021",
"typeofattendence": 0
}
]
Here is my fetch data please note I can post single json data not able to post multiple.Here is my code
body: JSON.stringify({
rollno: this.state.data,
typeofattendence: this.state.value
})` `body: JSON.stringify({
rollno: this.state.data,
typeofattendence: this.state.value
})
Please help me . Here you can see I can post single json object but how i post inside array multiple object . Thanks in advance
You should store your object in an array first.
For example.
let data = [];
data.push({
rollno: this.state.data,
typeofattendence: this.state.value
});
and when you want to send it to the server
body: JSON.stringify(data);
You can use:
var myarray = [];
var myJSON = "";
var item = {
"rollno": "10",
"typeofattendence": 1
};
myarray.push(item);
item = {
"rollno": "10021",
"typeofattendence": 0
}
myarray.push(item);
myJSON = JSON.stringify({myarray: myarray});
As this http://jsfiddle.net/jensbits/MWSeg/ toturial says.

Categories

Resources