Hi all how do i create a model class with this kind of response in swift using SiwftJson am not sure how to include this
"total_songs": 12,
"title": "Arun Thapa",
"result": "success",
"favorite": "false",
"cover": "artists/4096759431451532756hqdefault.jpg" in model using below response
{
"total_favorite": 0,
"Data": [
[
{
"album_song_id": "120",
"artist_name": "Arun Thapa",
"status": "1",
"song_duration": "245213",
"song_favorite": "false",
"albumb_name": "Arun Thapa",
"created_by": "1",
"created_at": "0000-00-00 00:00:00",
"albumb_id": "42",
"chart_name": "Evergreen Songs",
"song_lyrics": "<html>\r\n<head>\r\n\t<title></title>\r\n</head>\r\n<body></body>\r\n</html>\r\n"
}
]
"total_songs": 12,
"title": "Arun Thapa",
"result": "success",
"favorite": "false",
"cover": "artists/4096759431451532756hqdefault.jpg"
}
thanks in advance
This is an example how to map JSON to a struct. I hope you can start with this piece of code.
Pay attention to optional and not-optional values.
struct SomeDataModel {
let totalFavorites: Int
let totalSongs: Int
// other properties go here
init(withJson json: JSON) {
self.totalFavorites = json["total_favorites"].intValue
self.totalSongs = json["total_songs"].intValue
// initialization of other properties go here
}
}
First of all your JSON data missing "]," in end of "Data".
So correct JSON according me :
{
"total_favorite": 0,
"Data": [
[
{
"album_song_id": "120",
"artist_name": "Arun Thapa",
"status": "1",
"song_duration": "245213",
"song_favorite": "false",
"albumb_name": "Arun Thapa",
"created_by": "1",
"created_at": "0000-00-00 00:00:00",
"albumb_id": "42",
"chart_name": "Evergreen Songs",
"song_lyrics": "<html>\r\n<head>\r\n\t<title></title>\r\n</head>\r\n<body></body>\r\n</html>\r\n"
}
]
],
"total_songs": 12,
"title": "Arun Thapa",
"result": "success",
"favorite": "false",
"cover": "artists/4096759431451532756hqdefault.jpg"
}
And i suggest one json To Swift model converter, you need to just simple put JSON and you get swift model file.
If you don't need extra code you can remove it from swift model file.
Link of JSON to SWIFT MODEL CONVERTER - http://www.json4swift.com
Related
Following huobi API, I subscribe to the trade.detail channel, and among one day data, I got one entry like this:
{
"ch": "market.BTC-USDT.trade.detail",
"ts": 1666158766936,
"tick": {
"id": 118671341528,
"ts": 1666158766920,
"data": [
{
"amount": 2,
"quantity": 0.002,
"trade_turnover": 38.4776,
"ts": 1666158766920,
"id": 1186713415280000,
"price": 19238.8,
"direction": ""
}
]
}
}
the direction field is empty string, don't know which side it is.
I'm very new to OpenAPI and I'm using http://editor.swagger.io to design an API.
I'm stuck in Schema with a JSON looking like following
{
"CORRELATION_ID": "10",
"CONTROL":
{
"DAS_IS_RECIPIENT": "123",
"DOCTPYE": "ert",
"PROCESS_INDICATOR": "nord"
},
"HEADER":
{
"ID": "456",
"INVOICE_NUMBER": "678",
"DMS_DOC_ID": "876",
"INVOICE_DATE": "10082020"
},
"ITEMS": [
{
"SHORT_TEXT": "123",
"LSTAR": 0,
"QUANTITY": "23"
},
{
"SHORT_TEXT": "456",
"LSTAR": 234,
"QUANTITY": "21"
}
],
"DEBITOR":
{
"ID": "444",
"FIRSTNAME": "nick",
"LASTNAME": "cantre"
},
"CREDITOR":
{
"ID": "454",
"FIRSTNAME": "ava",
"LASTNAME": "pierre"
}
}
How to create a schema according to this JSON structure?
The default result of rendering FastJsonApi gem serialized_json like below:
render json: FlashcardSerializer.new(flashcards).serialized_json
would be something like this:
{
"data": [
{
"id": "1",
"type": "flashcard",
"attributes": {
"question": "why?",
"answer": "pretty good",
"slug": null
}
},
{
"id": "2",
"type": "flashcard",
"attributes": {
"question": "What is 0",
"answer": "it is 0",
"slug": null
}
}
]
}
I would rather add some extra information especially for pagination and I like the result to be something like this:
{
"data": [
{
"id": "1",
"type": "flashcard",
"attributes": {
"question": "why?",
"answer": "pretty good",
"slug": null
}
},
{
"id": "2",
"type": "flashcard",
"attributes": {
"question": "What is 0",
"answer": "it is 0",
"slug": null
}
},
"count":100,
"page":1,
]
}
I am aware of other available gems that manage pagination in API, and I know how to do it without Fastjson. The main issue here is that is there any way to get the aforementioned result from this gem without changing a lot in the code. Thanks
The desired document would be invalid according to the JSON API specification. You would need to include next and previous links in a link section. The current and total_count would belong in the meta section.
{
"data": [
{
"id": "1",
"type": "flashcard",
"attributes": {
"question": "why?",
"answer": "pretty good",
"slug": null
}
},
{
"id": "2",
"type": "flashcard",
"attributes": {
"question": "What is 0",
"answer": "it is 0",
"slug": null
}
},
]
"meta": {
"page": { "current": 1, "total": 100 }
},
"links": {
"prev": "/example-data?page[before]=yyy&page[size]=1",
"next": "/example-data?page[after]=yyy&page[size]=1"
},
}
Have a look at the JSON API specification before you continue designing the API.
You can pass these information into the serializer as an options argument
class FlashcardsController < ApplicationController
def index
render json: FlashcardSerializer.new(
flashcards, { links: {}, meta: { page: { current: 1 } }
).serialized_json
end
end
How you generate the data depends what you use to paginate.
If you design a new API, I would also recommend to use cursor based pagination rather than offset pagination because of it's limitations.
https://github.com/Netflix/fast_jsonapi#compound-document
https://github.com/Netflix/fast_jsonapi/blob/master/spec/lib/object_serializer_spec.rb#L8-L32
I am trying to poll the GitHub API for issues and print them out. To do so, I need to deserialize a nested JSON structure that I receive from a cURL GET request.
I am trying to get the url for all the objects in the items array:
{
"total_count": 4905,
"incomplete_results": false,
"items": [
{
"url": "https://api.github.com/repos/servo/saltfs/issues/789",
"repository_url": "https://api.github.com/repos/servo/saltfs",
"labels_url":
"https://api.github.com/repos/servo/saltfs/issues/789/labels{/name}",
"comments_url": "https://api.github.com/repos/servo/saltfs/issues/789/comments",
"events_url": "https://api.github.com/repos/servo/saltfs/issues/789/events",
"html_url": "https://github.com/servo/saltfs/issues/789",
"id": 293260512,
"number": 789,
"title": "Stop setting $CARGO_HOME to its default value",
"user": {
"login": "SimonSapin",
"id": 291359,
"avatar_url": "https://avatars0.githubusercontent.com/u/291359?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/SimonSapin",
"html_url": "https://github.com/SimonSapin",
"followers_url": "https://api.github.com/users/SimonSapin/followers",
"following_url": "https://api.github.com/users/SimonSapin/following{/other_user}",
"gists_url": "https://api.github.com/users/SimonSapin/gists{/gist_id}",
"starred_url": "https://api.github.com/users/SimonSapin/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/SimonSapin/subscriptions",
"organizations_url": "https://api.github.com/users/SimonSapin/orgs",
"repos_url": "https://api.github.com/users/SimonSapin/repos",
"events_url": "https://api.github.com/users/SimonSapin/events{/privacy}",
"received_events_url": "https://api.github.com/users/SimonSapin/received_events",
"type": "User",
"site_admin": false
},
"labels": [
{
"id": 341722396,
"url": "https://api.github.com/repos/servo/saltfs/labels/E-easy",
"name": "E-easy",
"color": "02e10c",
"default": false
}
],
"state": "open",
"locked": false,
"assignee": null,
"assignees": [
],
"milestone": null,
"comments": 0,
"created_at": "2018-01-31T18:16:09Z",
"updated_at": "2018-01-31T18:16:49Z",
"closed_at": null,
"author_association": "MEMBER",
"body": "In `buildbot/master/files/config/environments.py` we set `CARGO_HOME` to Cargo’s default value. Now that `mach` does not set it (since https://github.com/servo/servo/pull/19395), this has no effect. We can remove these lines.",
"score": 1.0
},
{
"url": "https://api.github.com/repos/servo/servo/issues/19916",
"repository_url": "https://api.github.com/repos/servo/servo",
"labels_url": "https://api.github.com/repos/servo/servo/issues/19916/labels{/name}",
"comments_url": "https://api.github.com/repos/servo/servo/issues/19916/comments",
"events_url": "https://api.github.com/repos/servo/servo/issues/19916/events",
"html_url": "https://github.com/servo/servo/issues/19916",
"id": 293237180,
"number": 19916,
"title": "Use a macro to create null-terminated C strings",
"user": {
"login": "jdm",
"id": 27658,
"avatar_url": "https://avatars1.githubusercontent.com/u/27658?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/jdm",
"html_url": "https://github.com/jdm",
"followers_url": "https://api.github.com/users/jdm/followers",
"following_url": "https://api.github.com/users/jdm/following{/other_user}",
"gists_url": "https://api.github.com/users/jdm/gists{/gist_id}",
"starred_url": "https://api.github.com/users/jdm/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/jdm/subscriptions",
"organizations_url": "https://api.github.com/users/jdm/orgs",
"repos_url": "https://api.github.com/users/jdm/repos",
"events_url": "https://api.github.com/users/jdm/events{/privacy}",
"received_events_url": "https://api.github.com/users/jdm/received_events",
"type": "User",
"site_admin": false
},
"labels": [
{
"id": 89384911,
"url": "https://api.github.com/repos/servo/servo/labels/C-assigned",
"name": "C-assigned",
"color": "02d7e1",
"default": false
},
{
"id": 15997664,
"url": "https://api.github.com/repos/servo/servo/labels/E-easy",
"name": "E-easy",
"color": "02e10c",
"default": false
},
{
"id": 135307111,
"url": "https://api.github.com/repos/servo/servo/labels/I-cleanup",
"name": "I-cleanup",
"color": "e11d21",
"default": false
}
],
"state": "open",
"locked": false,
"assignee": null,
"assignees": [
],
"milestone": null,
"comments": 3,
"created_at": "2018-01-31T17:04:06Z",
"updated_at": "2018-01-31T22:03:56Z",
"closed_at": null,
"author_association": "MEMBER",
"body": "When we write them by hand (eg. `b\"some string\\0\"`), we invariably get them wrong in ways that are tricky to notice (https://github.com/servo/servo/pull/19915). We should use a macro like this instead:\r\n```rust\r\nmacro_rules! c_str {\r\n ($str:expr) => {\r\n concat!($str, \"\\0\").as_bytes()\r\n }\r\n}\r\n```\r\nThis would allow us to write code like `(c_str!(\"PEParseDeclarationDeclExpected\"), Action::Skip)` instead of https://github.com/emilio/servo/blob/d82c54bd3033cc3277ebeb4854739bebe4e20f2f/ports/geckolib/error_reporter.rs#L237. We should be able to clean up all of the uses in that file.\r\n\r\nNo need to run any automated tests; if it builds with `./mach build-geckolib`, then it's good enough for a pull request.",
"score": 1.0
}
]}
My request function makes a cURL request and receives the above JSON. I then use serde_json to deserialize the JSON
main.rs
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
mod engine;
mod server;
use engine::request;
use std::string::String;
use self::serde_json::{Error, Value};
#[derive(Serialize, Deserialize)]
struct obj {
items: Vec<String>,
}
fn main() {
let output_jn: String = request(
"https://api.github.com/search/issues?q=is:issue+label:e-easy",
).to_string(); //gets json structure as string
let json: obj = serde_json::from_str(&output_jn).unwrap();
for elem in json.iter() {
println!("{:?}", elem);
}
}
I get the following error message
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:
ErrorImpl { code: Message("invalid type: map, expected a sequence"),
line: 1, column: 0 }', libcore/result.rs:945:5
note: Run with `RUST_BACKTRACE=1` for a backtrace.
I'm certain I'm making a stupid mistake in deserializing my JSON structure, I've tried a number of permutations and combinations but I couldn't get anything to work.
Have a look at this part of your JSON input data:
{
...
"items": [
{
...
"title": "Stop setting $CARGO_HOME to its default value",
...
}
]
}
The top-level data structure is a JSON map, so in Rust this will be represented as a struct. I will use your name Obj.
The top-level JSON map has a key called "items" so in Rust this will be a field items inside the Obj struct.
The value of "items" in the map is a JSON array, so in Rust let's use a Vec.
Each element in the JSON array is a JSON map so in Rust we need a struct for those. We can call it Issue.
Each issue has a JSON key called "title" so this will be a field title inside the Issue struct.
The value of "title" is a JSON string so we can use Rust's String type for the field.
#[derive(Deserialize, Debug)]
struct Obj {
items: Vec<Issue>,
}
#[derive(Deserialize, Debug)]
struct Issue {
title: String,
}
fn main() {
let j = /* get the JSON data */;
let issues = serde_json::from_str::<Obj>(j).unwrap();
for i in issues.items {
println!("{:#?}", i);
}
}
I'm playing around with the SoundCloud iOS tutorial and have been changing the API calls to get different information.
However, I can't seem to get any JSON back for a call I make to the API when I try to do a GET request on the URL https://api.soundcloud.com/me/activities/tracks/affiliated.json. The GET request works in the API console. Other GET requests work too, so I'm thinking that it's the definitely the way I'm asking for information in Xcode.
Here's the "Money" part of the program - gets the data, parses, creates a new view controller that has an array as a property with the response.
SCRequestResponseHandler handler;
handler = ^(NSURLResponse *response, NSData *data, NSError *error) {
NSError *jsonError = nil;
NSJSONSerialization *jsonResponse = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&jsonError];
if (!jsonError && [jsonResponse isKindOfClass:[NSArray class]]) {
UIStoryboard *sb = self.storyboard;
SCTTrackListViewController *trackListVC;
trackListVC = [sb instantiateViewControllerWithIdentifier:#"TLVC"];
trackListVC.tracks = (NSArray *)jsonResponse;
// Am I getting JSON back for tracks/affiliated.json ?
NSLog(#"json %#",(NSArray *)jsonResponse);
[self presentViewController:trackListVC
animated:YES
completion:nil];
}
};
NSString *resourceURL = #"https://api.soundcloud.com/me/activities/tracks/affiliated.json";
[SCRequest performMethod:SCRequestMethodGET
onResource:[NSURL URLWithString:resourceURL]
usingParameters:nil
withAccount:account
sendingProgressHandler:nil
responseHandler:handler];
}
If I use NSString *resourceURL = #"https://api.soundcloud.com/me/tracks.json"; or NSString *resourceURL = #"https://api.soundcloud.com/me/favorites.json"; then I get a list of tracks returned in JSON. If I use the one in the code example, I get no response - total silence.
The JSON response I get for https://api.soundcloud.com/me/favorites.json is in the form of
[
{
"kind": "track",
"id": 112547469,
"created_at": "2013/09/26 06:50:06 +0000",
"user_id": 294371,
"duration": 4499751,
"commentable": true,
"state": "finished",
"original_content_size": 143977742,
"sharing": "public",
"tag_list": "Funk Disco",
"permalink": "the-boogie-down",
"streamable": true,
"embeddable_by": "all",
"downloadable": false,
"purchase_url": null,
"label_id": null,
"purchase_title": null,
"genre": "Boogie",
"title": "The Boogie Down",
"description": "1.\tWar - The World Is A Ghetto (Suonho Edit)\r\n\r\n2. \tWhiskey Barons - The Same Love\r\n\r\n3.\tRayko - Broadway\r\n\r\n4.\tNicholas - Talking About Love\r\n\r\n5.\tBen E. King - Supernatural Thing (Fingerman Edit)\r\n\r\n6.\tGazeebo - Scaredy Cat\r\n\r\n7.\tFingerman - Fat Like You Know\r\n\r\n8.\tWillie Beaver - Party Time (Karim Edit)\r\n\r\n9.\tDeadly Sins - I Can Feel It\r\n\r\n10.\tFingerman - Tootin\r\n\r\n11.\tRocco Raimundo - Give Me Your Love\r\n\r\n12.\tLuther Vandross - Never Too Much\r\n\r\n13.\tKool & The Gang - Get Down On It (Rocco Raimundo Edit)",
"label_name": "",
"release": "",
"track_type": "",
"key_signature": "",
"isrc": "",
"video_url": null,
"bpm": null,
"release_year": null,
"release_month": null,
"release_day": null,
"original_format": "mp3",
"license": "all-rights-reserved",
"uri": "https://api.soundcloud.com/tracks/112547469",
"user": {
"id": 294371,
"kind": "user",
"permalink": "web_d",
"username": "webd",
"uri": "https://api.soundcloud.com/users/294371",
"permalink_url": "http://soundcloud.com/web_d",
"avatar_url": "https://i1.sndcdn.com/avatars-000011907556-1k1cgw-large.jpg?3eddc42"
},
"user_playback_count": 1,
"user_favorite": true,
"permalink_url": "http://soundcloud.com/web_d/the-boogie-down",
"artwork_url": "https://i1.sndcdn.com/artworks-000058671332-jzz9uc-large.jpg?3eddc42",
"waveform_url": "https://w1.sndcdn.com/qA5zJCmDqO46_m.png",
"stream_url": "https://api.soundcloud.com/tracks/112547469/stream",
"playback_count": 69,
"download_count": 0,
"favoritings_count": 1,
"comment_count": 0,
"attachments_uri": "https://api.soundcloud.com/tracks/112547469/attachments"
},
whilst the response for https://api.soundcloud.com/me/activities/tracks/affiliated.json goes:
{
"collection": [
{
"type": "track",
"created_at": "2013/10/08 20:14:16 +0000",
"origin": {
"kind": "track",
"id": 114421587,
"created_at": "2013/10/08 18:20:21 +0000",
"user_id": 144598,
"duration": 340616,
"commentable": true,
"state": "finished",
"original_content_size": 13624479,
"sharing": "public",
"tag_list": "",
"permalink": "faden-away",
"streamable": true,
"embeddable_by": "all",
"downloadable": false,
"purchase_url": null,
"label_id": null,
"purchase_title": null,
"genre": "Funk",
"title": "Faden Away",
"description": "",
"label_name": "",
"release": "",
"track_type": "",
"key_signature": "",
"isrc": "",
"video_url": null,
"bpm": null,
"release_year": null,
"release_month": null,
"release_day": null,
"original_format": "mp3",
"license": "all-rights-reserved",
"uri": "https://api.soundcloud.com/tracks/114421587",
"user": {
"id": 144598,
"kind": "user",
"permalink": "stonesthrow",
"username": "Stones Throw Records",
"uri": "https://api.soundcloud.com/users/144598",
"permalink_url": "http://soundcloud.com/stonesthrow",
"avatar_url": "https://i1.sndcdn.com/avatars-000001771161-2x04bn-large.jpg?3eddc42"
},
"user_playback_count": 1,
"user_favorite": false,
"permalink_url": "http://soundcloud.com/stonesthrow/faden-away",
"artwork_url": "https://i1.sndcdn.com/artworks-000059640743-qtexag-large.jpg?3eddc42",
"waveform_url": "https://w1.sndcdn.com/NBZ15f1BZ4cV_m.png",
"stream_url": "https://api.soundcloud.com/tracks/114421587/stream",
"playback_count": 29756,
"download_count": 0,
"favoritings_count": 1587,
"comment_count": 138,
"attachments_uri": "https://api.soundcloud.com/tracks/114421587/attachments",
"sharing_note": {
"text": "",
"created_at": "2013/10/08 20:14:16 +0000"
}
},
"tags": "affiliated"
},
{
"type": "track",
"created_at": "2013/10/08 14:26:00 +0000",
"origin": {
"kind": "track",
"id": 112820793,
"created_at": "2013/09/27 21:39:16 +0000",
"user_id": 1520490,
"duration": 290926,
"commentable": true,
"state": "finished",
"original_content_size": 12579855,
"sharing": "public",
"tag_list": ""MUSEUM OF LOVE" "DFA RECORDS" "PAT MAHONEY" "LCD SOUNDSYSTEM" "THE JUAN MACLEAN" JEE DAY DFA",
"permalink": "museum-of-love-monotronic",
"streamable": true,
"embeddable_by": "all",
"downloadable": false,
"purchase_url": "https://itunes.apple.com/album/monotronic-single/id711563768",
"label_id": null,
"purchase_title": "DIGITAL SINGLE",
"genre": "",
"title": "Museum of Love - Monotronic",
"description": "Museum Of Love\n"Monotronic"\n\nDFA2390\n\nfirst single "Down South" available here: http://store.dfarecords.com/products/dfa2389",
"label_name": "DFA Records",
"release": "DFA2390",
"track_type": "original",
"key_signature": "",
"isrc": "",
"video_url": "http://www.youtube.com/watch?v=K2E6oK7tN5w",
"bpm": null,
"release_year": 2013,
"release_month": 10,
"release_day": 8,
"original_format": "mp3",
"license": "all-rights-reserved",
"uri": "https://api.soundcloud.com/tracks/112820793",
"user": {
"id": 1520490,
"kind": "user",
"permalink": "dfa-records",
"username": "DFA Records",
"uri": "https://api.soundcloud.com/users/1520490",
"permalink_url": "http://soundcloud.com/dfa-records",
"avatar_url": "https://i1.sndcdn.com/avatars-000002067008-el39h6-large.jpg?3eddc42"
},
"user_playback_count": 1,
"user_favorite": false,
"permalink_url": "http://soundcloud.com/dfa-records/museum-of-love-monotronic",
"artwork_url": "https://i1.sndcdn.com/artworks-000058798982-ogzv3j-large.jpg?3eddc42",
"waveform_url": "https://w1.sndcdn.com/0m0pwUhjvenc_m.png",
"stream_url": "https://api.soundcloud.com/tracks/112820793/stream",
"playback_count": 10047,
"download_count": 0,
"favoritings_count": 309,
"comment_count": 18,
"attachments_uri": "https://api.soundcloud.com/tracks/112820793/attachments",
"sharing_note": {
"text": "",
"created_at": "2013/09/27 21:39:16 +0000"
}
},
"tags": "affiliated"
},
I'm trying to store the response in an NSArray, and I think that might be the issue... can someone point me in the right direction to get the JSON for affiliated.json? Is the response of the second JSON a dictionary? Do I need to store the response for that one differently? I thought I could store a dictionary in an NSArray...
The reason I was getting back nothing was due to this line: NSLog(#"json %#",(NSArray *)jsonResponse); where I was casting jsonResponse as an NSArray. This worked in the first instance because the response was an array, but in the second instance the response was a dictionary. Pretty obvious now that I think about it. I changed that line to (NSDictionary *)jsonResponse and all was well.
After I received the JSON data, this was also a good way to experiment with the different ways to dig into the nested info in the data. For instance, I created a dictionary to hold jsonResponse. I could get the info for the key I wanted in a couple of ways:
dictionary[#"user"][#"avatar_url] would get the nested value for avatar_url which was itself nested in user.
I could also do this by calling [dictionary valueForKeyPath:#"user.avatar_url"];