Using Alamofire and SwiftyJSON subscripts in Swift 3

For some reason, my code isn't working as expected and the result is always nil. I have incorporated Alamofire and SwiftyJSON into my code. Here is a snippet:

let urlString = "myurl"

let params: Parameters = [
    "accessProvider": AccessProvider,
    "inputToken": AccessToken
]


Alamofire.request(urlString, method: .post, parameters: params, encoding: URLEncoding.httpBody)
    .responseJSON { response in
        if let responseObject = response.result.value {
            print("JSON: \(responseObject)")

            let json = JSON(responseObject)

            let path: [JSONSubscriptType] = ["user","id"]
            let name = json[path].string
            print("AAAAA")
            print(name)
        }
}

I am able to retrieve information from the first part of the user object, but the second part containing the id is always returning nil. Here is the JSON response being received:

{
  "responseCode": 0,
  "responseDescription": "OK",
  "user": "{"id":"MAIL",
        "nickname":"MYNAME",
        "level":"U",
        "status":"A",
        "sex":null,
        "ageGroup":null,
        "address":null,
        "latitude":null,
        "longitude":null,
        "creation_timestamp":"2017-05-10 18:40:21",
        "notification":"1",
        "last_login":"2017-05-11 18:32:07",
        "mobilePreference":null,
        "sport":null,
        "spot":null,
        "token":"LONGTOKENID"}"
}

Answer №1

Appreciation to vadian for the help, I successfully resolved the issue with your guidance, For those facing a similar problem, here is the solution: //Creating the initial JSON:

let json = JSON(responseObject)

//Extracting the second JSON as a String

let path: [JSONSubscriptType] = ["user"]
let name = json[path].string

//Converting the extracted string into a new JSON

if let dataFromString = name?.data(using: .utf8, allowLossyConversion: false) 
let jsonuser = JSON(data: dataFromString)

//Accessing the data within the JSON

Thanks to everyone who contributed, Have a great day ahead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

gson returns null if not deserialized

Issue with Gson deserialization when not handling specific fields public class Mode { @Expose(deserialize = false) public final List<String> list; public Mode(List<String> list) { this.list = list; } public List< ...

Error: Unable to extract 'blog' property from 'param' because it is not defined in the Strapi NextJS context

I'm currently developing a blog using NextJS and Strapi. While implementing the comment functionality for my blog posts, I encountered two strange errors: TypeError: Cannot destructure property 'blog' of 'param' as it is undefined. ...

There was a problem encountered while trying to import Json data

I'm having trouble importing my JSON file into R. I've installed the necessary packages and here's what I attempted: library(rjson) JsonData <- fromJson(file= "<filename.json>") I also tried using the file path and the jsonlite pa ...

Display a message after serializing JSON in my cakePHP application

Is there a way to append something at the conclusion of the cakePHP json/xml output? This is necessary for incorporating JSONP capability (Since I must insert the callback at the start and ');' at the end) This is how the controller is set up: ...

Guide to Retrieving Response Data and Converting it into HTTP Header Manager in JMeter

After running the Login sampler, I received the following result: [Login Sampler Result Data][1] In this output, I need to extract "access_token":"91kLM68tdMBoDFRURArvdmwYgWV9Nr2sHYDwivTM" and store the value "91kLM68tdMBoDFRURArvdmwYgWV9Nr2sHYDwivTM" ...

Tips for transferring data via ajax to rails 3. The jQuery function is ensuring the string is properly handled

I am attempting to achieve the following: $.ajax({ type: "PUT", url: /example, data: {_method: "put", "foo_model[bar_attribute]": value_var } }); It is working as expected, but I need to dynamically construct the part foo_model[bar_attribute]. ...

Parsing JSON in PHP to extract individual array values

Recently delving into PHP, I encountered a JSON file that I successfully decoded and stored as shown below: $jsonInput = '[{"b_pag_bo_id":"31","b_pag_user_id":"1","b_pag_id":"1","b_page_mark":"1","b_pag_num":"3","b_pag_note":"","b_page_stop":"1"},{"b ...

Decoding a JSON response requires understanding the structure and content of

[ { "property1": "prop-00000001", "property2": "property2value1", "property3": {}, "property4": [ "Prop4-00000001", "Prop4-00000002" ] }, { "property1": "prop-00000002", ...

Converting JSON to parquet format or not converting at all, the choice

We have encountered a situation where converting a JSON file to parquet results in the creation of numerous small parquet files. How can we prevent this from happening? What is the most effective and efficient approach to managing this transformation? Bel ...

Error in decoding JSON while creating an index in Azure Search

I'm currently utilizing the django framework and attempting to set up an index in the Azure portal through their REST API guide. However, upon sending my post request, I encountered the following error: JSONDecodeError at /createIndex Here is the m ...

Converting an object with a System.Drawing.Image into a json format

I'm facing a bit of a challenge and struggling to find a solution... Within my interface (and implemented class), there is an image property... Guid uid { get; set; } Image imageData1 { get; set; } string fileName { get; set; } The imag ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

Just dipping my toes into the world of backend development and diving into the intric

Hi everyone, I've been working on coding for a little over a year now and have mainly focused on frontend technologies like JavaScript, various frameworks, CSS, and HTML. Just yesterday, I encountered the notorious CORS issue with the Spotify API. Ev ...

What is the best way to perform an AJAX request in Typescript with JSON data?

Currently, I am delving into the realm of AJAX and encountering some hurdles when attempting to execute an AJAX request with parameters. Specifically, I am facing difficulties in sending JSON data: My approach involves utilizing Typescript in tandem with ...

php generate JSON response as an array

I'm struggling with creating a JSON array that should have this structure: error : false duellid : 1 questions : [ { questionid : xx question : lala answer : blabla }, { questionid : xx question : lala a ...

Utilizing JSON to transfer PHP array data for display using JQuery

Currently, I am working on a jQuery script that is responsible for fetching a PHP array from the MySQL database and converting it into a JSON object. The process is functioning correctly, as I can successfully output the raw JSON data along with the keys. ...

Can the values in all fields of a JSON be combined or subtracted with those of another object containing the same fields?

I am currently working with a Mongoose.js schema that is structured as follows: { "City": String, "Year": String, "Population": Number, "Blah": Number, "Nested": { "Something": Number, "More stuff": Number } } Is there an efficient w ...

Retrieving information from database with the help of PHP and AJAX

I am having trouble printing data from a PHP and Ajax request that is initially encoded into JSON. Instead of displaying the data properly on the screen, it is showing elements from four rows all in a single line with commas separating them. $(document ...

Insert a new element into a JSON array using C#

I have a JSON Array here and I am looking to append a new field into the array. However, I am unsure of how to iterate over it. { "data": { "pasca": [ { "code": "PDI1231", ...

I am having trouble authorizing a GET request with fetch

I've been attempting to utilize fetch in the browser, but it's not cooperating. Here's what I tried: fetch('https://api-2sizcg3ipa-uc.a.run.app/fats', { headers: {'Authorization': 'Basic ' + btoa('username ...