How to convert the JSON response to Map in Flutter - flutter

I have a JSON response from my API call. The format is like this.
[
{
"hotelname": "A",
"roomno": "101",
"occupancy": "4"
},
{
"hotelname": "A",
"roomno": "102",
"occupancy": "3"
},
{
"hotelname": "B",
"roomno": "101",
"occupancy": "4"
},
{
"hotelname": "B",
"roomno": "202",
"occupancy": "3"
}
]
I want to write a code where in one dropdown list displays the names of the hotels(A,B,C etc) the other dropdown should display the corresponding roomno.
To achieve this i would like to convert my JSON response to a MAP like the below.
Map<String,String> _hoteldata = {
"101":"A",
"102":"A",
"101":"B",
"202":"B",
};

First, you parse the json using jsonDecode(), then create a map from the list, for example, using Map.fromEntries():
import 'dart:convert';
var rooms = jsonDecode(json) as List;
var hotelData = Map.fromEntries(
rooms.map((room) => MapEntry(room['roomno'], room['hotelname']))
);

Related

How remove the specific value from map in dart?

I am Beginner in flutter, learning map concept. I am confusing map methods. How to delete a specific value from a map?
for example:
Map data = {
"studet1": {"name": "ajk", "age": "22", "place": "delhi"},
"studet2": {"name": "akmal", "age": "25", "place": "up"}
};
I want to delete the "name" from "student1".
data is a nested map, which means that it has another map within the key of student1.
You can use the .remove method to remove a key within a map:
Removes key and its associated value, if present, from the map.
void main() {
Map data ={
"student1":{
"name" : "ajk",
"age":"22",
"place":"delhi"
},
"student2":{
"name" : "akmal",
"age":"25",
"place":"up"
}
};
data['student1'].remove('name');
print(data);
}
Prints:
{student1: {age: 22, place: delhi}, student2: {name: akmal, age: 25, place: up}}
If you want to remove only student1 name
Just use data['student1'].remove('name');
Or if you want to remove all students name use the bleow method
Map data = {
"studet1": {"name": "ajk", "age": "22", "place": "delhi"},
"studet2": {"name": "akmal", "age": "25", "place": "up"}
};
for (int i = 0; i <= data.length - 1; i++) {
data[data.keys.elementAt(i)].remove('name');
}
The output will be
{student1: {age: 22, place: delhi}, student2: {age: 25, place: up}}

print data form List of Maps flutter/

I need to print startTime form this Map of decodedData.
I am new to flutter .
I need startTime so that I can show the time slots for availability.
Map decodedData = { "sts" : "SUCCESS", "data" : [{
"startTime": 1665392445000,
"between": 1665414045000
},
{
"startTime": 1665414045000,
"between": 1665414045000
},
]};
List<String> arrayStartTime = (decodedData["data"] as List<Map<String,dynamic>>).map((e) => "${e['startTime']}").toList();
result:
[1665392445000, 1665414045000]
You can set array int or String type as per your requirement
You must try this :
decodedData["data"]).values.forEach((v) => print("startTime =
${v["startTime"]}"));
You can use decodedData[0]['startTime'] and so on, you can also use for loop.
and use
DateTime.fromMillisecondsSinceEpoch(decodedData[0]['startTime'],isUtc: true).toString() to print it or format it as per your need.
Try this:
Map decodedData = { "sts" : "SUCCESS", "data" : [{
"slotKey": "1665392445000_|_1665394245000",
"startTime": 1665392445000,
"endTime": 1665394245000,
"isbooked": true,
"bookedBy": "qxWESdGsHvhywe3S7FxDeO2"
},
{
"slotKey": "1665414045000_|_1665415845000",
"startTime": 1665414045000,
"endTime": 1665415845000,
"isbooked": false
},
]};
void main(){
for(var item in decodedData["data"]){
print("startTime = ${item["startTime"]}");
}
}

use JsLookup for multiple level array using play Json for lists with objects and simple lists

i have a function that exctract from a json list of elements based on the path i give it.
the func looks like this:
def findAllValuesAtPath(jsValue: JsObject, path: String): List[JsValue] = {
val jsPath = JsPath(path
.split("\\[\\*]\\.")
.flatMap(s => s.split("\\.")
.map(RecursiveSearch)
).toList)
jsPath(jsValue)
}
for example:
{
"person": {
"kids": [
{
"name": "josh",
"age": 5
},
{
"name": "julia",
"age": 13
}
]
}
}
now if i give the path - "person.kids[*].name" I will get list of their names List("josh", "julia") which its what i want.
but if the list of kids were just simple list like:
{
"person": {
"kids": [
"josh",
"julia"
]
}
}
and i will give the path - "person.kids[*]" I will get empty list List() and I want to get this as List("josh", "julia") (without the brakets)
do you see any way to improve my func to handle both cases?

How to convert inner json part into object in dart/flutter

I need to convert every element of 'content' array to object.
Here is json:
{
"content": [
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"author": {
"userId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
},
"createDate": "2020-01-30T20:18:29.764Z",
"executor": {
"userId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
},
}
],
"first": true,
"numberOfElements": 0,
}
The problem is that 'content' array is inside json, and its parts as executor and author has to be objects too, and I don't know how to reach it and parse.
How it can be done? Any help, thanks.
You access the elements like this:
var decoded = json.decode(j);
var inner = decoded['content'][0]; // if you expect more than one entry, iterate the list
print(inner['id']); // -> 3fa85f64-5717-4562-b3fc-2c963f66afa6
print(inner['createDate']);
print(inner['author'].runtimeType); // another Map<String, dynamic> as expected
print(inner['author']['userId']);
You can create Dart classes to model, for example, a 'user' if you want.

Decode a nested array with circe-optics

I have JSON like this:
"data": {
"project": {
"activityChildren": [
{
"id": 2,
"parents": [
{
"id": 1
}
]
},
]
}
}
I'd like to decode this to List[(Long, List[Long])] with circe-optics. I got as far as:
val activityParents: Map[Long, List[Long]] = root.data.activityChildren.each.json
.getAll(json)
.flatMap { activity =>
root.id.long.getOption(activity).map(_ -> root.parents.each.long.getAll(activity))
}
.toMap
I wonder whether it's possible to define a single lens for this that just turns the JSON into the desired map without explicitly mapping over the intermediate array. If so, how?