Swifty JSON Response Parsing - json

I am using SwiftyJson. I am getting a response from printing.
{ "coin" : 120 }
I want to store this response in a variable. How can I store this value in a variable?

To get the specific value from response, it's related with type of response.
https://grokswift.com/json-swift-4/
For example, if response is JSON Array, Please try this.
let val = response[index][key]
otherwise,
let val = response[key1][key2][..]

Related

Save JSON Response as Variable to Deserialise with SwiftyJSON

I'm going to use either SwiftyJSON or EasyFastMapping to deserialise JSON data into variables and constants but I'm not sure on how to save the whole JSON file into its own object, if it is even possible.
I will be using Alamofire to handle the GET request and pull the JSON data down, is it possible to do it like this?
How I want it to work:
1. Alamofire pulls down the JSON data
Alamofire puts the data into an object
SwiftyJSON accesses the downloaded data and allows me to put individual parts of the data into separate variables and constants.
You could take a look at the documentation for SwiftyJSON and Alamofire and you will find plenty of examples.
From Alamofire Readme:
Alamofire.request("https://httpbin.org/get").responseJSON { response in
debugPrint(response)
if let json = response.result.value {
print("JSON: \(json)")
}}
From SwiftJSON Readme:
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
//Your implementation here
}
You can also create a separate response object and deserialize all the response JSON into the object. Also take a look at the built-in JSONSerialization API in the Foundation framework.

How to post values from RestAssured to JSon and get a value from it?

{"service_request": {"service_type":"Registration","partner":"1010101","validity":1,"validity_unit":"Year","quantity":1,"center":"1020301","template":"2020301"}}
I have JSON values as above obtained from Request Payload, when I post data from the web page. I want to post this data from RESTAssured in java and want to get the returned value? How can I do that?
I would recommend to check https://github.com/jayway/rest-assured/wiki/Usage#specifying-request-data
I imagine you are trying to do a POST using Rest-Assured.For that simplest and easy way is.. Save your payload as String. If you have payload as JSONObject, use toJSONString() to convert it to String
String payload = "yourpayload";
String responseBody = given().contentType(ContentType.JSON).body(payload).
when().post(url).then().assertThat().statusCode(200).and()
extract().response().asString();
Above code, post your payload to given Url, verify response code and convert response body to a String. You can do assertion without converting to String as well like
given().contentType(ContentType.JSON).body(payload).
when().post(url).then().assertThat().statusCode(200).
and().assertThat().body("service_request.partner", equalTo("1010101"));

Parsing JSON with SwiftyJSON

I'm having trouble parsing the following JSON file with SwiftyJSON. I've looked around the web and tried different suggested solutions with no luck.
Here is the JSON:
{'info-leag':{'Status':1,'Name':'Testing Name','url-lig':'test.testing.com','uid':'12345'}}
And my relevant code:
//initializes request
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.currentQueue()) { response, maybeData, error in
if let data = maybeData {
let json = JSON(data: data)
//stores data as UTF8 String
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
The first part seems to work fine, I am able to get the JSON and save it as data, at the bottom I converted it to a string to make sure that I was getting the right information, I then later print it to make sure.
I tried different things like:
let name = json["info-league"]["Name"] //can't seem to get the context
I'm trying to get the Name and uid to be saved as 2 strings as well as the Status as an int.
Thanks!
Once you've made your JSON valid like this:
{"info-league":{"Status":1,"Name":"Testing Name","url-lig":"test.testing.com","uid":"12345"}}
you will be able to use your example, it works (I just tested):
let name = json["info-league"]["Name"]
but it's better to use SwiftyJSON types:
let name = json["info-league"]["Name"].string
let status = json["info-league"]["Status"].int
so your variables are of known types for later use.
If you don't do this they will be of type JSON, a type created by SwiftyJSON, and you will have to cast them later (not a problem, depends how you're organised in your code).
Try:
let name = json["info-league"]["Name"].string

Parse an entire JSON array into a table using 1 key

I need some help with parsing JSON in Swift.
[{"Database":"information_schema"}
{"Database":"Tonysnasa"},
{"Database":"camaleonsystems"},
{"Database":"camaleonsystems_back"},
{"Database":"camaleonsystemsfortest"}]
^ - Above is my JSON
v - Below is my Swift code.
let jsonDB: String! = jsonResult[0]["Database"] as NSString
println(jsonDB)
self.DBList.append(jsonDB)
I want to parse all of the "Database:" entries. When I try the method above, I am only able to parse information_schema.
How can I parse all the "Database:"'s into my table?
looks like it is an array of dictionaries,to get them all you should be able to use:
var jsonDB : [Dictionary<String, String>] = jsonResult
for currentDictionary in jsonDB{
var currentEntry = currentDictionary["Database"] as String
println(currentEntry)
self.DBList.append(currentEntry)
}

Couchbase - deserialize json into dynamic type

I'm trying to deserialize some JSON coming back from couchbase into a dynamic type.
The document is something like this so creating a POCO for this would be overkill:
{
UsersOnline: 1
}
I figured that something like this would do the trick, but it seems to deserialize into a dynamic object with the value just being the original JSON
var jsonObj = _client.GetJson<dynamic>(storageKey);
results in:
jsonObj { "online": 0 }
Is there anyway I can get the couchbase deserializer to generate the dynamic type for me?
Cheers
The default deserializer for the client uses .NET's binary serializer, so when you save or read a JSON string, it's just a string. GetJson will always just return a string. However, there are a couple of options:
You could convert JSON records to Dictionary instances:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
var item = client.GetJson<Dictionary<string, object>>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item["UsersOnline"], item["NewestMember"]);
Or you could use a dynamic ExpandoObject instance:
var appJson = "{ \"UsersOnline\" : 1, \"NewestMember\" : \"zblock\" }";
var result = client.ExecuteStore(StoreMode.Set, "userCount", appJson);
dynamic item = client.GetJson<ExpandoObject>("userCount");
Console.WriteLine("There are {0} users online. The newest member is {1}.",
item.UsersOnline, item.NewestMember);
In either case you're losing static type checking, which seems like it's OK for your purposes. In both cases you get access to the JSON properties without having to parse the JSON into a POCO though...
Edit: I wrote a couple of extension methods that may be useful and blogged about them at http://blog.couchbase.com/moving-no-schema-stack-c-and-dynamic-types