How I can get all the values in this JSON and add all the value in to the list of object in the dart?
"data": [
{
"$id": "2",
"serviceId": 1017,
"name": "اکو",
"code": "235",
"price": 1562500,
"isDefault": true,
"transportCostIncluded": false,
"qty": 0,
"minQty": 1,
"maxQty": 2,
"description": "یک دستگاه اکو به همراه دو باند و یک عدد میکروفن (تامین برق بعهده پیمانکار می باشد).",
"contractorSharePercent": 65,
"unitMeasureId": 7,
"unitMeasureName": "هر 60 دقیقه",
"superContractorsId": null
},
],
like this var list = ["2",1017,....]
CodePudding user response:
Assuming you've a JSON file, which you may have parsed like this:
String json = await rootBundle.loadString('file_name.json');
var response = jsonDecode(json);
This is how you can do it:
List<dynamic> jsonData; //similar to var jsonData = [something, something, ...]
//traversing through each value in the key value arrangement of the json
for (var k in response.values) {
jsonData.add(k); //adding each value to the list
}
After the loop ends, jsonData
will have all the values of your JSON file.
CodePudding user response:
It's important for you to know that even if you put the keys on a list, they won't necessarily be in order, because of the way maps work.
Assuming your json is a map and not a json string, you could put all of the values on a list like so:
var myList = (jsonObject['data'] as List).fold<List>(
[],
(prev, curr) => [...prev, ...curr.values]
);
if you were talking about a json string:
Map<String, dynamic> jsonObject = jsonDecode(jsonString);
CodePudding user response:
For simplicity, lets assume this json is unparsed in a string.
(1) Assuming the code snippet you added is a string && is valid json you can do as follows :)
import 'dart:convert';
void main() {
var x = json.decode('''
{
"data": [
{
"hello": "2",
"serviceId": 1017,
"name": "اکو",
"code": "235",
"price": 1562500,
"isDefault": true,
"transportCostIncluded": false,
"qty": 0,
"minQty": 1,
"maxQty": 2,
"description": "یک دستگاه اکو به همراه دو باند و یک عدد میکروفن (تامین برق بعهده پیمانکار می باشد).",
"contractorSharePercent": 65,
"unitMeasureId": 7,
"unitMeasureName": "هر 60 دقیقه",
"superContractorsId": null
}
]
}
''');
print(x);
List<dynamic> listOfObjects = (x['data'] as Iterable<dynamic>).toList();
/// this is just gonna be a list of all of your object.
print(listOfObjects);
List<dynamic> listOfValues = (x['data'] as Iterable<dynamic>).map((_object) {
return (_object as Map<String, dynamic>).values.toList();
}).toList();
/// this is gonna be a 2d array here,
print(listOfValues);
}
Hope This helped out:)
Also json here comes from import 'dart:convert';