How to parse json data in swiftui` [closed] - swift

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 days ago.
Improve this question
I am working on an iOS application in which I have to fetch data.
As I can see this url contain JSON data so here should I need to parse it or not I am not getting it how to get this JSON data.
Here is my code.
import SwiftUI
struct Dashboard: View {
#State private var receives = [Receive]()
var body: some View {
List(receives, id: \.id){ item in
VStack{
Text(item.createdAt)
}
}.task {
await loadData()
}
}
func loadData() async {
guard let url = URL(string: "https://******/dashboard")
else{
print("iii")
return
}
var request = URLRequest(url: url)
request.setValue("s", forHTTPHeaderField: "Authorization")
do{
let (data,_) = try await URLSession.shared.data(from: url)
print(data.count)
let decodedResponse = try? JSONDecoder().decode(Welcome.self, from: data)
print("klllll")
receives = (decodedResponse?.data.receives ?? [])!
print(receives)
}
catch{
print("invalid")
}
}
}
Model Class :
import Foundation
struct Welcome: Codable {
let success: Bool
let message: String
let data: DataClass
}
struct DataClass {
let quickStats: QuickStats
let receives: [Receive]
}
But Im getting Output:
6609
[]
JSON Response:
{
"success": true,
"message": "Dashboard details",
"data": {
"quickStats": {
"buyCnt": 3,
"sellCnt": 0,
"openCnt": 0,
"pendingCnt": 0,
"completeCnt": 1
},
"advertisments": [
{
"id": 8,
"crypto_currency_id": 7,
"trade_by": 4,
"trade_type": "1",
"location": "mdu",
"country": "1",
"market": "5",
"margin": "15",
"trade_price": 10,
"trade_total": null,
"min_transaction_limit": 1,
"max_transaction_limit": 16,
"total_limit": 16,
"total_trade_amount": null,
"crypto_coin_amount_price": null,
"payment_window": 1,
"payment_method": "a",
"account_details": "d",
"additional_information": "d",
"terms": "mm",
"is_feedback": 0,
"status": 0,
"created_at": "2023-02-15",
"updated_at": "2023-02-15T05:31:12.000000Z",
"slug": ""
},
{
"id": 5,
"crypto_currency_id": 1,
"trade_by": 4,
"trade_type": "Buy",
"location": "demo",
"country": "98",
"market": "74",
"margin": "1.2",
"trade_price": 15375.35,
"trade_total": null,
"min_transaction_limit": 100,
"max_transaction_limit": 1000,
"total_limit": 1000,
"total_trade_amount": null,
"crypto_coin_amount_price": null,
"payment_window": 15,
"payment_method": "1",
"account_details": "demo",
"additional_information": "demo",
"terms": "demo",
"is_feedback": 0,
"status": 0,
"created_at": "2023-01-28",
"updated_at": "2023-01-28T14:42:52.000000Z",
"slug": "BTC"
},
{
"id": 4,
"crypto_currency_id": 1,
"trade_by": 4,
"trade_type": "Buy",
"location": "demo",
"country": "98",
"market": "98",
"margin": "1.2",
"trade_price": 1254583.09,
"trade_total": null,
"min_transaction_limit": 10,
"max_transaction_limit": 100,
"total_limit": 100,
"total_trade_amount": null,
"crypto_coin_amount_price": null,
"payment_window": 15,
"payment_method": "1",
"account_details": "demo",
"additional_information": "demo",
"terms": "demo",
"is_feedback": 0,
"status": 0,
"created_at": "2023-01-28",
"updated_at": "2023-01-28T14:02:46.000000Z",
"slug": "BTC"
},
{
"id": 3,
"crypto_currency_id": 3,
"trade_by": 4,
"trade_type": "Buy",
"location": "demo",
"country": "22",
"market": "102",
"margin": "1.2",
"trade_price": 0.89,
"trade_total": null,
"min_transaction_limit": 10,
"max_transaction_limit": 100,
"total_limit": 100,
"total_trade_amount": null,
"crypto_coin_amount_price": null,
"payment_window": 15,
"payment_method": "1",
"account_details": "demo",
"additional_information": "demo",
"terms": "demo",
"is_feedback": 0,
"status": 0,
"created_at": "2023-01-28",
"updated_at": "2023-01-28T14:00:59.000000Z",
"slug": "BUSD"
}
],
"receives": [
{
"id": 7,
"trade_order_id": 11,
"sender_id": 4,
"receiver_id": 4,
"is_trusted_user": 0,
"is_distrusted_user": 1,
"feedback_score": 4,
"message": "test",
"status": 1,
"created_at": "2023-01-28T14:27:04.000000Z",
"updated_at": "2023-01-28T14:27:04.000000Z",
"username": "smith",
"image": "https://new.demozab.com/armup/api/public//userpanel/images/profile.svg"
}
]
}
}

Related

Parse nested json tree using flutter

I have a json nested tree that looks like this :
{
"children": [
{
"children": [],
"id": 9,
"level": 1,
"name": "Zone d'audit Interne"
},
{
"children": [],
"id": 10,
"level": 1,
"name": "Magasin PF"
},
{
"children": [],
"id": 11,
"level": 1,
"name": "Magasin MP"
},
{
"children": [
{
"children": [],
"id": 14,
"level": 2,
"name": "Packaging"
},
{
"children": [],
"id": 15,
"level": 2,
"name": "Labelling"
},
{
"children": [],
"id": 16,
"level": 2,
"name": "Assemblage Acc"
}
],
"id": 12,
"level": 1,
"name": " U4: Assembalge Finale"
},
{
"children": [
{
"children": [],
"id": 18,
"level": 2,
"name": "Contrôle traitement"
},
{
"children": [],
"id": 19,
"level": 2,
"name": "Tunnel de Séchage"
},
{
"children": [],
"id": 20,
"level": 2,
"name": "Traitement Mécanique"
}
],
"id": 17,
"level": 1,
"name": "U3: Traitement"
},
{
"children": [
{
"children": [],
"id": 23,
"level": 2,
"name": "Ass_Ligne 2"
},
{
"children": [],
"id": 24,
"level": 2,
"name": "Ass_ligne 1"
},
{
"children": [],
"id": 39,
"level": 2,
"name": "BU"
}
],
"id": 21,
"level": 1,
"name": "U2: Assemblage SF"
},
{
"children": [
{
"children": [],
"id": 26,
"level": 2,
"name": "Mgasin Tampon"
},
{
"children": [],
"id": 27,
"level": 2,
"name": "Contrôle Kitting"
}
],
"id": 25,
"level": 1,
"name": "U1: Kitting"
},
{
"children": [],
"id": 35,
"level": 1,
"name": "to-delete"
}
],
"id": 8,
"level": 0,
"name": "DEMO"
}
I've tried parsing it but I only figured out how to parse the first level.
I want to be able to parse it and print / use every node's level .
if possible I want to turn it into a list of objects so I can use it in my widgets,
If anyone can help I'd be grateful
here's how am parsing it :
Future<Map<String, dynamic>?> fetchPerimeterTree(
{required int id, required String baseUrl}) async {
try {
final request = http.Request(
'GET', Uri.parse("$baseUrl${Endpoints.fetchPerim}$id/json"));
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
debugPrint("Perimeters tree fetched with success");
var jsonData = jsonDecode(await response.stream.bytesToString());
List<dynamic> fetchData2 = jsonData["children"];
fetchData2.forEach((element) {
print(element["name"]);
print(element["children"]);
print(element["level"]);
});
print(fetchData2);
return jsonData;
} else {
throw Exception('Failed to load perimeter tree ${response.statusCode}');
}
} catch (ex) {
debugPrint(ex.toString());
}
}
Assumed your json called jsonData, and define a class model like this:
class ChildModel {
final int id;
final int level;
final String name;
final List<ChildModel>? children;
ChildModel(
{required this.id,
required this.level,
required this.name,
this.children});
static ChildModel fromJson(Map<String, dynamic> json) {
List children = json["children"] as List;
return ChildModel(
id: json["id"],
level: json["level"],
name: json["name"],
children: children.isNotEmpty
? children.map((e) => ChildModel.fromJson(e)).toList()
: []);
}
}
then you can get your data like this:
ChildModel result = ChildModel.fromJson(jsonData);
and you can test it like this:
print(" name = ${result.children?[3].children?[0].name}"); // name = Packaging
In this way you can cache all the layers of children.

RangeError (end): Invalid value: Only valid value is 0: 1 when generating model

Getting the error RangeError (end): Invalid value: Only valid value is 0: 1 when generating model when I try to generate model
Expected Behavior
when I use this command get generate model on match_details with assets/models/to_get/match_details.json
it should be creating a model inside the match_details folder with the fields inside the JSON file mentioned.
Current Behavior
When I try to do this I get the error RangeError (end): Invalid value: Only valid value is 0: 1 when generating model** when I try to generate model
Possible Solution
Am sure it is something about parsing the JSON file
More info
here is what the JSON file looks like
{
"success": true,
"details": {
"id": 22,
"date_time": "2022-04-12T20:00:00Z",
"home_team": {
"id": 69,
"home_strip": {
"id": 15,
"image": "/uploads/strip_5_0py3QXM.png"
},
"away_strip": {
"id": 16,
"image": "/uploads/WhatsApp_Image_2022-03-09_at_10.24.56_AM.jpeg"
},
"players": [{
"id": 47,
"is_cap": false,
"average_skill": 3,
"region": {
"id": 13,
"name_ar": "التجمع الخامس",
"name_en": "Fifth Settlement",
"state": {
"id": 8,
"name_ar": "القاهره",
"name_en": "Cairo"
}
},
"first_name": "Ezz El Din",
"last_name": "Karim",
"mobile": "01113481110",
"email": null,
"image": null,
"positions_ar": [{
"مدافع": 3
}],
"positions_en": [{
"CB": 3
}],
"basic_skills_ar": [{
"السرعة": 4
},
{
"تمرير الكرة": 3
},
{
"تسديد": 2
}
],
"basic_skills_en": [{
"speeding": 4
},
{
"Passing": 3
},
{
"shooting": 2
}
]
}],
"cap": {
"id": 46,
"is_cap": true,
"average_skill": 3,
"region": {
"id": 13,
"name_ar": "التجمع الخامس",
"name_en": "Fifth Settlement",
"state": {
"id": 8,
"name_ar": "القاهره",
"name_en": "Cairo"
}
},
"first_name": "Karim",
"last_name": "Garrana",
"mobile": "01113332257",
"email": "karim.garrana#gmail.com",
"image": null,
"positions_ar": [{
"مهاجم": 3
},
{
"مدافع": 4
}
],
"positions_en": [{
"ST": 3
},
{
"CB": 4
}
],
"basic_skills_ar": [{
"السرعة": 3
},
{
"تمرير الكرة": 3
},
{
"تسديد": 3
}
],
"basic_skills_en": [{
"speeding": 3
},
{
"Passing": 3
},
{
"shooting": 3
}
]
},
"average_skill": 3,
"points": 0,
"name": "كوبرا",
"league": 25,
"logo": "/uploads/9_IApeihR.png",
"region_ar": "التجمع الخامس",
"region_en": "Fifth Settlement"
},
"away_team": {
"id": 68,
"home_strip": {
"id": 14,
"image": "/uploads/strip_6.png"
},
"away_strip": {
"id": 13,
"image": "/uploads/strip_5.png"
},
"players": [{
"id": 46,
"is_cap": true,
"average_skill": 3,
"region": {
"id": 13,
"name_ar": "التجمع الخامس",
"name_en": "Fifth Settlement",
"state": {
"id": 8,
"name_ar": "القاهره",
"name_en": "Cairo"
}
},
"first_name": "Karim",
"last_name": "Garrana",
"mobile": "01113332257",
"email": "karim.garrana#gmail.com",
"image": null,
"positions_ar": [{
"مهاجم": 3
},
{
"مدافع": 4
}
],
"positions_en": [{
"ST": 3
},
{
"CB": 4
}
],
"basic_skills_ar": [{
"السرعة": 3
},
{
"تمرير الكرة": 3
},
{
"تسديد": 3
}
],
"basic_skills_en": [{
"speeding": 3
},
{
"Passing": 3
},
{
"shooting": 3
}
]
}],
"cap": {
"id": 45,
"is_cap": false,
"average_skill": 4,
"region": {
"id": 11,
"name_ar": "ميامى",
"name_en": "Miami",
"state": {
"id": 7,
"name_ar": "الإسكندرية",
"name_en": "Alexandria"
}
},
"first_name": "Ahmed",
"last_name": "Wagdi",
"mobile": "01207199086",
"email": "ahmed.w.amin#gmail.com",
"image": "/uploads/90f1e1c9-b430-4f9c-8347-a86be57f58676954964268664537546.jpg",
"positions_ar": [{
"مدافع": 5
}],
"positions_en": [{
"CB": 5
}],
"basic_skills_ar": [{
"تسديد": 5
},
{
"تمرير الكرة": 5
},
{
"السرعة": 5
}
],
"basic_skills_en": [{
"shooting": 5
},
{
"Passing": 5
},
{
"speeding": 5
}
]
},
"average_skill": 4,
"points": 2,
"name": "المنتقمون",
"league": 25,
"logo": "/uploads/6.png",
"region_ar": "التجمع الخامس",
"region_en": "Fifth Settlement"
},
"location": {
"id": 8,
"name_ar": "مدرسة الكابيتال",
"name_en": "Capital School",
"location": "30.014650515430546,31.4582347869873",
"region": 13
}
}
}

How to get all the files from the Moodle assignment in a course?

I want to get all the files from an assignment in Moodle. Is there a way to get all the files?
When I call core_course_get_contents from my local Moodle instance as
http://localhost:8077/webservice/rest/server.php?wstoken=11e2d8b7f8e21ca1804e41e9cac5a816&wsfunction=core_course_get_contents&courseid=4&moodlewsrestformat=json
I receive the response as:
[
{
"id": 22,
"name": "General",
"visible": 1,
"summary": "",
"summaryformat": 1,
"section": 0,
"hiddenbynumsections": 0,
"uservisible": true,
"modules": []
},
{
"id": 23,
"name": "Introduction",
"visible": 1,
"summary": "",
"summaryformat": 1,
"section": 1,
"hiddenbynumsections": 0,
"uservisible": true,
"modules": [
{
"id": 44,
"url": "http://localhost:8077/mod/assign/view.php?id=44",
"name": "Assignment",
"instance": 3,
"contextid": 99,
"visible": 1,
"uservisible": true,
"visibleoncoursepage": 1,
"modicon": "http://localhost:8077/theme/image.php/boost/assign/1613571924/icon",
"modname": "assign",
"modplural": "Assignments",
"indent": 0,
"onclick": "",
"afterlink": null,
"customdata": "\"\"",
"noviewlink": false,
"completion": 1,
"completiondata": {
"state": 0,
"timecompleted": 0,
"overrideby": null,
"valueused": false
}
},
{
"id": 46,
"url": "http://localhost:8077/mod/resource/view.php?id=46",
"name": "test(.txt)",
"instance": 24,
"contextid": 102,
"visible": 1,
"uservisible": true,
"visibleoncoursepage": 1,
"modicon": "http://localhost:8077/theme/image.php/boost/core/1613571924/f/text-24",
"modname": "resource",
"modplural": "Files",
"indent": 0,
"onclick": "",
"afterlink": null,
"customdata": "\"a:1:{s:10:\\\"printintro\\\";i:1;}\"",
"noviewlink": false,
"completion": 1,
"completiondata": {
"state": 0,
"timecompleted": 0,
"overrideby": null,
"valueused": false
},
"contents": [
{
"type": "file",
"filename": "test.txt",
"filepath": "/",
"filesize": 935,
"fileurl": "http://localhost:8077/webservice/pluginfile.php/102/mod_resource/content/1/test.txt?forcedownload=1",
"timecreated": 1621949734,
"timemodified": 1621949744,
"sortorder": 1,
"mimetype": "text/plain",
"isexternalfile": false,
"userid": 2,
"author": "ABC",
"license": "unknown"
}
],
"contentsinfo": {
"filescount": 1,
"filessize": 935,
"lastmodified": 1621949744,
"mimetypes": [
"text/plain"
],
"repositorytype": ""
}
}
]
}
]
I want to get the files from the assignment. Is there a way to achieve this?

How to retrieve Forum/discussion attachments of a course in Moodle LMS?

I have to list all the attachments of a discussion in a course. I don't know how to retrieve all the attachments URLs in a forum/discussion in Moodle LMS.
My code is in c# and usually, I call the Moodle REST API as http://localhost:8077/webservice/rest/server.php?wstoken=11e2d8b7f8e21ca1804e41e9cac5a812&wsfunction=core_course_get_contents&courseid=4&moodlewsrestformat=json and I can get the fileurl for the course files.
Likewise, I would like to retrieve forum/discussion files but I don't see any fileurl or something similar.
I only see the response as below:
[
{
"id": 22,
"name": "General",
"visible": 1,
"summary": "",
"summaryformat": 1,
"section": 0,
"hiddenbynumsections": 0,
"uservisible": true,
"modules": []
},
{
"id": 23,
"name": "Introduction",
"visible": 1,
"summary": "",
"summaryformat": 1,
"section": 1,
"hiddenbynumsections": 0,
"uservisible": true,
"modules": [
{
"id": 46,
"url": "http://localhost:8077/mod/resource/view.php?id=46",
"name": "Everest (.txt)",
"instance": 24,
"contextid": 102,
"visible": 1,
"uservisible": true,
"visibleoncoursepage": 1,
"modicon": "http://localhost:8077/theme/image.php/boost/core/1613571924/f/text-24",
"modname": "resource",
"modplural": "Files",
"indent": 0,
"onclick": "",
"afterlink": null,
"customdata": "\"a:1:{s:10:\\\"printintro\\\";i:1;}\"",
"noviewlink": false,
"completion": 1,
"completiondata": {
"state": 0,
"timecompleted": 0,
"overrideby": null,
"valueused": false
},
"contents": [
{
"type": "file",
"filename": "Everest.txt",
"filepath": "/",
"filesize": 935,
"fileurl": "http://localhost:8077/webservice/pluginfile.php/102/mod_resource/content/1/Everest.txt?forcedownload=1",
"timecreated": 1621949734,
"timemodified": 1621949744,
"sortorder": 1,
"mimetype": "text/plain",
"isexternalfile": false,
"userid": 2,
"author": "DP Bhatt",
"license": "unknown"
}
],
"contentsinfo": {
"filescount": 1,
"filessize": 935,
"lastmodified": 1621949744,
"mimetypes": [
"text/plain"
],
"repositorytype": ""
}
},
{
"id": 47,
"url": "http://localhost:8077/mod/forum/view.php?id=47",
"name": "Forum",
"instance": 5,
"contextid": 112,
"visible": 1,
"uservisible": true,
"visibleoncoursepage": 1,
"modicon": "http://localhost:8077/theme/image.php/boost/forum/1613571924/icon",
"modname": "forum",
"modplural": "Forums",
"indent": 0,
"onclick": "",
"afterlink": null,
"customdata": "\"\"",
"noviewlink": false,
"completion": 1,
"completiondata": {
"state": 0,
"timecompleted": 0,
"overrideby": null,
"valueused": false
}
}
]
}
]
It would be great if someone guides me on the right path. Thank you very much in advance.

FLUTTER: how ro format Open weather sunrise and sunshine data?

I'm trying to format the json data below to get time only. NOT time and date. But I havent been able to do it. How could you do it?
Thanks for the help.
Json Data from open weather:
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 300,
"main": "Drizzle",
"description": "light intensity drizzle",
"icon": "09d"
}
],
"base": "stations",
"main": {
"temp": 280.32,
"pressure": 1012,
"humidity": 81,
"temp_min": 279.15,
"temp_max": 281.15
},
"visibility": 10000,
"wind": {
"speed": 4.1,
"deg": 80
},
"clouds": {
"all": 90
},
"dt": 1485789600,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0103,
"country": "GB",
"sunrise": 1485762037,
"sunset": 1485794875
},
"id": 2643743,
"name": "London",
"cod": 200
}
This is the part I'd like to format:
"sys": {
"message": 0.0025,
"country": "JP",
"sunrise": 1485726240,
"sunset": 1485763863
}
I guess you can do something like this to parse the values for sunrise and sunset and get the hour and minute of each time. Take a look and please tell me if you want any changes:
import 'dart:convert';
void main() {
const jsonString = '''
{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 300,
"main": "Drizzle",
"description": "light intensity drizzle",
"icon": "09d"
}
],
"base": "stations",
"main": {
"temp": 280.32,
"pressure": 1012,
"humidity": 81,
"temp_min": 279.15,
"temp_max": 281.15
},
"visibility": 10000,
"wind": {
"speed": 4.1,
"deg": 80
},
"clouds": {
"all": 90
},
"dt": 1485789600,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0103,
"country": "GB",
"sunrise": 1485762037,
"sunset": 1485794875
},
"id": 2643743,
"name": "London",
"cod": 200
}
''';
dynamic jsonObject = jsonDecode(jsonString);
dynamic sys = jsonObject['sys'];
print(sys);
// {type: 1, id: 5091, message: 0.0103, country: GB, sunrise: 1485762037, sunset: 1485794875}
sys['sunrise'] = getClockInUtcPlus3Hours(sys['sunrise'] as int);
sys['sunset'] = getClockInUtcPlus3Hours(sys['sunset'] as int);
print(sys);
// {type: 1, id: 5091, message: 0.0103, country: GB, sunrise: 10:37, sunset: 19:55}
print(json.encode(sys));
// {"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":"10:37","sunset":"19:55"}
print('sunrise: ${getClockInUtcPlus3Hours(1485762037)}'); // sunrise: 10:37
print('sunset: ${getClockInUtcPlus3Hours(1485794875)}'); // sunset: 19:55
}
String getClockInUtcPlus3Hours(int timeSinceEpochInSec) {
final time = DateTime.fromMillisecondsSinceEpoch(timeSinceEpochInSec * 1000,
isUtc: true)
.add(const Duration(hours: 3));
return '${time.hour}:${time.second}';
}