Dart objects in Lists - arrays

Im new on dart/flutter.
how can i use objects in lists ?
i have objects like:
{
"channelName": "sydneyfunnelaio",
"type": "",
"ChannelPic": "https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
"success": true
}
how can i create list/array with that ;
I want like:
[{
"channelName": "sydneyfunnelaio",
"type": "",
"ChannelPic": "https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
"success": true
},{
"channelName": "qweqdqaw",
"type": "",
"ChannelPic": "https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
"success": true
}]

You can try something like this :
void main() {
List<MyObject> myObjects = [];
myObjects.add(MyObject.fromJson({
"channelName": "sydneyfunnelaio",
"type": "",
"ChannelPic":
"https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
"success": true
}));
myObjects.add(MyObject.fromJson({
"channelName": "qweqdqaw",
"type": "",
"ChannelPic":
"https://static-cdn.jtvnw.net/jtv_user_pictures/8ead1810-f82a-4dc0-a3a6-583171baff60-profile_image-300x300.jpeg",
"success": true
}));
print(myObjects);
print(myObjects[0].channelName);
print(myObjects[1].channelName);
myObjects.forEach((obj)=>print(obj.toJson()));
}
class MyObject {
String channelName;
String type;
String channelPic;
bool success;
MyObject({this.channelName, this.type, this.channelPic, this.success});
MyObject.fromJson(Map<String, dynamic> json) {
channelName = json['channelName'];
type = json['type'];
channelPic = json['ChannelPic'];
success = json['success'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['channelName'] = this.channelName;
data['type'] = this.type;
data['ChannelPic'] = this.channelPic;
data['success'] = this.success;
return data;
}
}

Related

Parsed Complex JSON Flutter

I am trying to parse this complex JSON data into a Flutter application. I am able to get the JSON data successfully, but not able to display the data in the application. See the code and JSON data below.
What I am doing wrong?
JSON Data
{
"response": {
"cars": [
[
{
"id": 1,
"name": "Ford Mustang GT",
"class": "Muscle Car"
},
{
"id": 2,
"name": "Dodge Challenger",
"class": "Muscle Car"
},
{
"id": 3,
"name": "Chevrolet Camaro",
"class": "Muscle Car"
},
{
"id": 4,
"name": "Pontiac Firebird",
"class": "Muscle Car"
}
]
]
}
}
Data Model
class Cars {
Cars({
this.id,
this.name,
this.carClass,
});
int id;
String name;
String carClass;
factory Cars.fromJson(Map<String, dynamic> json) => Cars(
id: json["id"],
name: json["name"],
carClass: json["class"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"class": carClass,
};
}
API Service getting the JSON Data
class ApiService {
Future<List<Cars>> getCars() async {
http.Response response = await http.get('http://localhost:3000/response');
var body;
if (response.statusCode == 200) {
body = jsonDecode(response.body);
List<dynamic> carList = body['response'];
print(body);
List<Cars> res =
carList.map((dynamic item) => Cars.fromJson(item)).toList();
return res;
}
}
}
Display Data
You can help in the construction of the classes with this application. (https://app.quicktype.io/)
These are the classes that you must use for the obtained object. Be sure to change the name of the classes that you think are relevant.
class Response {
Response({
this.response,
});
final ResponseClass response;
factory Response.fromJson(Map<String, dynamic> json) => Response(
response: ResponseClass.fromJson(json["response"]),
);
Map<String, dynamic> toJson() => {
"response": response.toJson(),
};
}
class ResponseClass {
ResponseClass({
this.cars,
});
final List<List<Car>> cars;
factory ResponseClass.fromJson(Map<String, dynamic> json) => ResponseClass(
cars: List<List<Car>>.from(json["cars"].map((x) => List<Car>.from(x.map((x) => Car.fromJson(x))))),
);
Map<String, dynamic> toJson() => {
"cars": List<dynamic>.from(cars.map((x) => List<dynamic>.from(x.map((x) => x.toJson())))),
};
}
class Car {
Car({
this.id,
this.name,
this.carClass,
});
final int id;
final String name;
final String carClass;
factory Car.fromJson(Map<String, dynamic> json) => Car(
id: json["id"],
name: json["name"],
carClass: json["class"],
);
Map<String, dynamic> toJson() => {
"id": id,
"name": name,
"class": carClass,
};
}
Finally, replace this line:
body = jsonDecode(response.body);
List<dynamic> carList = body['response'];
print(body);
List<Cars> res =
carList.map((dynamic item) => Cars.fromJson(item)).toList();
with this:
return Response.fromJson(response.body);
and replace the data type that the function returns to Response.
You can also follow the official documentation for flutter Serializtion. It's good and also saves us from the hassle of creating the conversion HashMaps.

How can I remove all JSON objects that have a certain key/value pair from an array of JSON objects?

I want to filter a dataset this like:
For example here's some fake dataset:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Donna",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Tia",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tuxedo"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
I want to filter out everything that has "livesInCity": false:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
How can I do this? Is this possible?
In python I believe it's something like this, but I do not know how to get started in Swift:
people = [person for person in people if person.livesInCity == True]
Also, how can I filter this data set above to look like this - I want to categorize by type in name.
{
"tabby": ["Sakura", "Linn"],
"tuxedo": ["Dora"],
}
Any help will be very appreciated!
As already mentioned in the comments, you can't work directly on JSON objects in Swift. They need to be converted first.
You can parse your JSON to a Swift object and then perform filtering, grouping etc.
struct Person: Codable {
let name: String
let hasChildren: Bool
let livesInCity: Bool
let pets: [Pet]
}
struct Pet: Codable {
let cats: [String]
let type: String
}
let jsonStr = "[{"name": "Sakura", ..." // your JSON string
let jsonData = jsonStr.data(using: .utf8)!
let parsedObjects = try! JSONDecoder().decode([Person].self, from: data)
Then you can filter your parsedObjects:
let filteredObjects = parsedObjects.filter({ person in person.livesInCity == true })
or in shorter (swiftier) version:
let filteredObjects = parsedObjects.filter { $0.livesInCity }
You can also try to group by pet type:
var groupedDict = [String:[String]]()
filteredObjects.forEach{ person in
person.pets.forEach { pet in
if let _ = groupedDict[pet.type] {
groupedDict[pet.type]!.append(person.name)
} else {
groupedDict[pet.type] = [person.name]
}
}
}
print(groupedDict)
//prints ["tabby": ["Sakura", "Linn"], "tuxedo": ["Dora"]]
If at any point you want to convert your objects back to JSON you can use:
let dictData = try! JSONEncoder().encode(groupedDict)
let dictStr = String(data: dictData, encoding: .utf8)!
print(dictStr)
//prints {"tabby":["Sakura","Linn"],"tuxedo":["Dora"]}
Note
For the sake of simplicity I used forced optional unwrapping (!) when decoding/encoding objects. You may want to use do-try-catch instead (to catch errors).

How to serialize api response contains list in flutter?

This is the response I am getting from server. All the properties are String and int expect data. It is a list of objects. When serializing the response it shows error. Please explain what is wrong with my code. I am from javascript background. Serialization in flutter is different from javascript.
class ResponseModel {
String image;
int row;
int column;
int position;
List<Data> data;
ResponseModel({this.image, this.row, this.column, this.position});
factory ResponseModel.fromJson(Map<String, dynamic> parsedJson) {
return ResponseModel(
image: parsedJson['image'],
row: parsedJson['row'],
column: parsedJson['column'],
position: parsedJson['position'],
);
}
}
class Data {
String imageUrl;
Data({this.imageUrl});
factory Data.fromJson(Map<String, dynamic> parsedJson) {
return Data(imageUrl: parsedJson["imageUrl"]);
}
}
[
{
"type": "image",
"row": 1,
"column": 3,
"position":"1",
"data": [
{
"imageUrl": "https://rukminim1.flixcart.com/flap/276/294/image/6dad06016c6ab319.jpg?q=90"
},
{
"imageUrl": "https://rukminim1.flixcart.com/flap/276/294/image/9ad209b0fc3d03e4.jpg?q=90"
},
{
"imageUrl": "https://rukminim1.flixcart.com/flap/276/294/image/405e10d01fae5aa5.jpg?q=90"
}
]
},
{
"type": "image",
"row": 1,
"column": 2,
"position":"3",
"data": [
{
"imageUrl": "https://rukminim1.flixcart.com/flap/414/630/image/f186565389063212.jpg?q=90"
},
{
"imageUrl": "https://rukminim1.flixcart.com/flap/414/630/image/3eda035d946b0ebf.jpg?q=90"
}
]
},
{
"type": "image",
"row": 1,
"column": 1,
"position":"2",
"data": [
{
"imageUrl": "https://rukminim1.flixcart.com/flap/1187/636/image/4436d492e2563998.jpg?q=90"
}
]
}
]
Future<dynamic> getData() async {
final response = await http.get("https://api.myjson.com/bins/1g4o04");
final parsedJson = json.decode(response.body);
final finalResponse = ResponseModel.fromJson(parsedJson);
print(finalResponse);
setState(() {
data = parsedJson;
});
}
Error image
You can use this tool and select dart Language
Its because the response is a JSON array. Which means json.decode(response.body) returns a List<dynamic> and hence the variable parsedJson is List.
You're trying to pass this List as a parameter to the ResponseModel.fromJson(Map<String, dynamic>) method which accepts a Map as the parameter.
In simple words, you're trying to pass a List where a Map is expected.
Future<dynamic> getData() async {
final response = await http.get("https://api.myjson.com/bins/1g4o04");
final parsedJson = json.decode(response.body);
List<ResponseModel> responseList = <ResponseModel>[];
parsedJson.foreach((element) {
responseList.add(ResponseModel.fromJson(element));
})
///Response list will have your data
print(responseList);
}
Your code should be something like this

Parse JSON array in side JSON array with List<Class> Flutter

I have JSON like this
{
"status": "true",
"data": [
{
"idpekerjaan": "1",
"namapekerjaan": "Apel Pagi / Sore",
"subpekerjaan": [
{
"idsubpekerjaan": "2",
"namasubpekerjaan": "Apel Pagi/Sore",
"standarwaktu": "15"
},
{
"idsubpekerjaan": "3",
"namasubpekerjaan": "Apel Pagi/Sore",
"standarwaktu": "20"
}
]
},
{
"idpekerjaan": "2",
"namapekerjaan": "Upacara",
"subpekerjaan": [
{
"idsubpekerjaan": "10",
"namasubpekerjaan": "Upacara",
"standarwaktu": "60"
},
{
"idsubpekerjaan": "11",
"namasubpekerjaan": "Upacara",
"standarwaktu": "90"
}
]
},
}
Saya mempunyai fungsi-fungsi:
class Localization {
final List <DataPekerjaan> pekerjaan;
final List <SubPekerjaan> subpekerjaan;
Localization({this.pekerjaan, this.subpekerjaan});
factory Localization.fromJson(Map<String, dynamic> json) {
return Localization(
subpekerjaan: parseStates(json),
pekerjaan: parseProvinces(json),
);
}
static List<SubPekerjaan> parseStates(statesJson) {
List<DataPekerjaan> cari = parseProvinces(statesJson);
var slist = ???????????????????? as List;
List<SubPekerjaan> statesList =
slist.map((data) => SubPekerjaan.fromJson(data)).toList();
return statesList;
}
static List<DataPekerjaan> parseProvinces(provincesJson) {
var plist = provincesJson['data'] as List;
List<DataPekerjaan> provincesList =
plist.map((data) => DataPekerjaan.fromJson(data)).toList();
return provincesList;
}
}
class SubPekerjaan {
final String idSubPekerjaan;
final String namaSubPekerjaan;
final String standarWaktu;
SubPekerjaan({this.idSubPekerjaan, this.namaSubPekerjaan, this.standarWaktu});
factory SubPekerjaan.fromJson(Map<String, dynamic> parsedJson){
return SubPekerjaan(idSubPekerjaan: parsedJson['idsubpekerjaan'], namaSubPekerjaan: parsedJson['namasubpekerjaan'], standarWaktu: parsedJson['standarwaktu']);
}
}
class DataPekerjaan {
final String idPekerjaan;
final String namaPekerjaan;
final List<String> subPekerjaan;
DataPekerjaan({this.idPekerjaan, this.namaPekerjaan, this.subPekerjaan});
factory DataPekerjaan.fromJson(Map<String, dynamic> parsedJson) {
return DataPekerjaan(idPekerjaan: parsedJson['idpekerjaan'], namaPekerjaan: parsedJson['namapekerjaan'], subPekerjaan: parsedJson["subpekerjaan"]);
}
}
I want to retrieve the contents of an array of data and then I create a List and then I also want to take the contents of an array of subpekerjaan so that it becomes a separate data. How can I insert each of those arrays into a function that I already have, especially in the ListparseStates (statesJson). What should I fill in the question mark?
Then is it true how I declare the data type List subPekerjaan on the DataPekerjaan class?
First your json is invalid (VAlidate at https://jsonlint.com/) it should be
{
"status": "true",
"data": [
{
"idpekerjaan": "1",
"namapekerjaan": "Apel Pagi / Sore",
"subpekerjaan": [
{
"idsubpekerjaan": "2",
"namasubpekerjaan": "Apel Pagi/Sore",
"standarwaktu": "15"
},
{
"idsubpekerjaan": "3",
"namasubpekerjaan": "Apel Pagi/Sore",
"standarwaktu": "20"
}
]
},
{
"idpekerjaan": "2",
"namapekerjaan": "Upacara",
"subpekerjaan": [
{
"idsubpekerjaan": "10",
"namasubpekerjaan": "Upacara",
"standarwaktu": "60"
},
{
"idsubpekerjaan": "11",
"namasubpekerjaan": "Upacara",
"standarwaktu": "90"
}
]
}
]
}
Now try with class
// To parse this JSON data, do
//
// final myModel = myModelFromJson(jsonString);
import 'dart:convert';
MyModel myModelFromJson(String str) => MyModel.fromJson(json.decode(str));
String myModelToJson(MyModel data) => json.encode(data.toJson());
class MyModel {
String status;
List<Datum> data;
MyModel({
this.status,
this.data,
});
factory MyModel.fromJson(Map<String, dynamic> json) => MyModel(
status: json["status"],
data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"status": status,
"data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
String idpekerjaan;
String namapekerjaan;
List<Subpekerjaan> subpekerjaan;
Datum({
this.idpekerjaan,
this.namapekerjaan,
this.subpekerjaan,
});
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
idpekerjaan: json["idpekerjaan"],
namapekerjaan: json["namapekerjaan"],
subpekerjaan: List<Subpekerjaan>.from(json["subpekerjaan"].map((x) => Subpekerjaan.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"idpekerjaan": idpekerjaan,
"namapekerjaan": namapekerjaan,
"subpekerjaan": List<dynamic>.from(subpekerjaan.map((x) => x.toJson())),
};
}
class Subpekerjaan {
String idsubpekerjaan;
String namasubpekerjaan;
String standarwaktu;
Subpekerjaan({
this.idsubpekerjaan,
this.namasubpekerjaan,
this.standarwaktu,
});
factory Subpekerjaan.fromJson(Map<String, dynamic> json) => Subpekerjaan(
idsubpekerjaan: json["idsubpekerjaan"],
namasubpekerjaan: json["namasubpekerjaan"],
standarwaktu: json["standarwaktu"],
);
Map<String, dynamic> toJson() => {
"idsubpekerjaan": idsubpekerjaan,
"namasubpekerjaan": namasubpekerjaan,
"standarwaktu": standarwaktu,
};
}

Get nested JSON object from a JSON Array

May i know how to get JSON object from an json array??
JSON:
[
{
"id": 1,
"user": {
"id": 20710,
"username": "abc",
"first_name": "",
"last_name": "",
},
"action": {
"name": "xxx",
"date": 19/01/01,
},
},
{
"id": 2,
"user": {
"username": "xyx",
"first_name": "xxx",
"last_name": "yyy",
},
"action": {
"name": "xxx",
"date": 19/05/01,
},
},]
I want to get username of these users in a list, but i cant get the value when i get this json from api as JSONArray.
My code:
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
Log.d("Create Response", response.toString());
ArrayList<String> list = new ArrayList<String>();
JSONArray jsonArray = response;
try {
if (jsonArray != null) {
int len = jsonArray.length();
for (int i=0;i<len;i++){
JSONObject c=response.getJSONObject(1);
String id = c.getString(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", id);
feeds_List.add(map);
}
}
I cannot use
JSONObject object=JsonArray.getJSONObject("user");
here,
it only accept int for getJSONObject("user"); if it is JSONArray
You can use like this also.Suppose response String is userInfo
ArrayList<String> usernames = new ArrayList<String>();
JSONArray userList = new JSONArray(userInfo);
for (int j = 0; j < userList.length(); j++) {
JSONObject userObject = new JSONObject(userList.getString(j));
String user = userObject.getString("user");
JSONObject usernameInfo = new JSONObject(user);
usernames.add(usernameInfo.getString("username"));
}
Try this, if not working please mention me in comment.

Resources