How to read data inside JSON object in swift - ios

[
{
"id": "dcf8df3f8ce5963d7fa8",
"title": "MySurvey",
"description": "Guest Survey"
}
]
Above is json data response from api. I've read above json data with SwiftyJSON in my ios project as follow.
let swiftyJsonVar = JSON(responseData.result.value!)
print(swiftyJsonVar["title"])
I can't read and print above json data. Please let me know how to read above json data with SwiftyJSON.

The response is Array not Dictionary, try to access this
let arr = swiftyJsonVar.arrayObject
print(arr[0]["title"])
print(arr[0]["id"])
print(arr[0]["description"])

Related

Alamofire 5.5 responseDecodable on JSON array

I am trying to decode an api response that just responds with an array. All the examples I see for using responseDecodable are a dictionary with a data key or something. But when I just pass [Movie].self into as the decoder I get:
failure(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.keyNotFound(CodingKeys(stringValue: "name", intValue: nil), Swift.DecodingError.Context(codingPath: responseDecodable
I'm assuming I'm not doing this right, looking for some help
GET /request
Response:
[{"id": 1, "name": "test"}]
struct Movie: Codable, Hashable {
let id: Int
let name: String
}
AF.request("http://localhost/request", parameters: parameters)
.responseDecodable(of: [Movie].self) { response in
debugPrint(response)
}
You will need to first assign a variable to accept the JSON data. From there, you can display the result. To illustrate:
AF.request("http://localhost/request", parameters: parameters)
.responseDecodable(of: [Movie].self) { response in
let myresult = try? JSON(data: response.data!)
then print it:
debugPrint(myresult)
If your JSON data is sound, then you should have no problem receiving the data. If your JSON is nested, then, you can drill-down into it:
let myresult = try? JSON(data: response.data!)
let resultArray = myresult!["result"]
and so on.
As for the "KeyNotFound" error ... It's because of what you said ... it's looking for a dictionary key/value pair. That should be resolved once you try the above example. Also, it's good practice to place your "method" in your AF request. :)
According to the error, your JSON didn't return a name value, so check that's it's actually supposed to be that key, or mark the value as optional if it's not always returned. let name: String?

How to insert and delete objects in json file swift

So I have this json which has an array of some objects.
[
{
"id": 1,
"title": "First Object"
},
{
"id": 2,
"title": "Second Object"
},
{
"id": 3,
"title": "Third Object"
}
]
I'm parsing the json with the following code,
struct MyModel: Codable {
let id: Int?
let title: String?
}
var myModel = [MyModel]()
func decodeData(url: URL) {
do {
let jsonData = try Data(contentsOf: url)
let decoder = JSONDecoder()
myModel = try decoder.decode([MyModel].self, from: jsonData)
} catch let jsonError {
print("Error serializing json", jsonError)
}
}
Everything works fine when it comes to reading the json. What I can seem to figure out is how to delete and insert object into the same json file.
For example, delete object with "id"=2, or insert a new object after object with "id"=3 or between objects with "id"=1 and "id"=2.
What I was thinking was to read the entire json file into an array. Then modify the data in the array by deleting and appending elements in the array then overwriting the json file with everything in the modified array.
For some reason this approach doesn't seem practical. Might be fine for a small numbers of objects but what happens if/when the number of objects reach a number in the 100+ range.
Am I taking the right approach by reading the contents of the json file into an array then modifying and overwriting the json file with the contents of the modify array or is there a proper way of achieving this?
You can delete any object from Dictionary using this piece of code, convert json to Dictionary.
if let index = values.index(forKey: id) {
values.remove(at: index)
}
and in the same way you can get the index of particular object where you want to insert new object.

Parsing json data using swift json

I can’t get the JSON data of message using swiftyjson.
When i print JSON value is there. But, when i print(json["result"]["message"]) it is null
{
"result": [{
"message": "success",
"age": "25"
}]
}
let json = JSON(data:jdata)
print(json)
print(json["result"]["message"])
json["result"] seems to be an array, you have to cast it to array like
let array = json["result"].arrayValue
let message = array[0]["message"]
You result is of array type. And you have to set index of object.
Try:
var array = json["result"].arrayValue
print(array[0]["message"])
You can also check this question
Hope it helps
Try:
let json = JSON(data: jdata)
let message = json["result"].array?.first?["message"]
print(message)

parse JSON Array from GET request Alamofire Swift 2

I'm new to Swift, my task is to get data from GET request and present its data on UI. Below is my code:
let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(.GET, myUrl, headers: headers)
.responseJSON{ JSON in
if let jsonResult = JSON as? Array<Dictionary<String, String>> {
let title = jsonResult[0]["title"]
print(title)
}
}
I'm able to get data with request but I don't know how to parse JSON object in some format (probably json array) that can be later used to present in TableView. Please help
Data example:
[
{
"title": "Sony",
"content": "Tech content",
"image": "http://google.com/content/device.jpg?06"
},
{
"title": "Nexus",
"content": "Nexus 6 is a new beginning",
"image": "http://google.com/content/device.jpg?01"
} ]
JSON data can be represented in different forms. It can be encoded as a string or converted into known data types on the platform. The main components of json are arrays, associative arrays (or dictionaries), and values.
The swift struct you are displaying reads as follows.
It's an array. Array content displayed here starts and ends with [] like [1,2,3] would be an array of ints.
The data in the the array a list of dictionaries. dictionary start and ends with {} . like {"key":"value"}
Those dictionaries contain the keys "title","content" and "image".
because you requested responseJSON from alamo file you will be returned a parsed structure and all you need to do read it like you would normal arrays and dictionaries as that is what it is.
You should read this documentation on how to make safe code that uses the above logic.
http://www.raywenderlich.com/82706/working-with-json-in-swift-tutorial

prolems in converting from json formatted String to json object

I have a web servlet that returns a json which is stored in my bb mobile app as string in json format....
Now I want to parse the string to extract values from it...
using
JSONObject jsobject = new JSONObject(jsonString);
returns an error:
json must start with {
My JSON generated is in this format
[
{"LASTNAME":"akre","FIRSTNAME":"swapnil"},
{"LASTNAME":"akre","FIRSTNAME":"swapnil"},
{"LASTNAME":"akre","FIRSTNAME":"swapnil"}
]
which is corect format as verified by jsonlint.com....
yes, json must start with { and end with } , what you can do is you put your json array in
{}, so it will be parsed correctly. JsonLint parses the partial json as well thats why it is showing it as correct. You can try like following
yes, json must start with { and end with } , what you can do is you put your json array in {}, so it will be parsed correctly as jsonobject. JsonLint parses the partial json as well thats why it is showing it as correct
{
"data": [
{
"LASTNAME": "akre",
"FIRSTNAME": "swapnil"
},
{
"LASTNAME": "akre",
"FIRSTNAME": "swapnil"
},
{
"LASTNAME": "akre",
"FIRSTNAME": "swapnil"
}
]
}
I'm assuming you're using this library.
Your JSON is an Array, so you'll have to use the JSONArray class to parse it

Resources