I have an optional parameter in my web-service response which can or can not return null. What will be the best what to manage those?
As if I pass null in creator lets say for this structure:
{
"email": "test#test.com",
"profilePicture": null,
"firstTime": true,
"preference1": {
"$id": "26",
"$values": []
},
"Preference2": {
"$id": "27",
"$values": []
}
}
Now profilePicture is set to JSONNull and next time when I actually get profile URL it will not parse that and my response data to LNUser is nil. If I set this variable to String and null received response get set to nil.
You need
let profilePicture:URL?
quicktype needs an exhaustive set of examples, so make sure one of your samples includes a non-null value. Like this: https://app.quicktype.io?share=ldXiDP9cIKB1Q7CPJ7Id
Related
I am getting a response from an API
["response": {
record = {
title = "Order Add";
usercart = 5345;
};
}, "status": success, "message": تم إضافة السجل بنجاح]
I got the Value for status Key from the code
let statusCode = json["status"].string
Now i want the value for the key usercart in string value
I am using this code but getting any response.
let order_id = json["response"]["record"]["usercart"].string
Please help me to get this value.
As you are using SwiftyJSON and you are trying to get usercart value as a string but the usercart is Int.
So if you want this in string formate you should need to use .stringValue instead of .string else you can use .int or .intValue in form of int.
json["response"]["record"]["usercart"].stringValue
The json you are getting from server is wrong. Instead it should be -
["response": {
"record" : {
"title" : "Order Add",
"usercart" : 5345
};
}, "status": success, "message": تم إضافة السجل بنجاح]
There is nothing like = in json
Also if server response cannot change I would suggest reading this whole thing as string and then using search in string, though it is very bad approach.
if you are using SwiftyJSON then use this to get value
json["response"]["record"]["usercart"].stringValue
I'm using this API to get a user's followers list, and returns the followers in JSON format as described in the documentation. Here is a snippet of a returned object:
{
"users": [
{
"id": 2960784075,
"id_str": "2960784075",
"name": "Jesus Rafael Abreu M",
"screen_name": "chuomaraver",
"location": "",
"profile_location": null,
"url": null,
"description": "",
"protected": false,
"followers_count": 1,
"friends_count": 101,
"listed_count": 0,
"created_at": "Sun Jan 04 19:58:06 +0000 2015",
.....
.....
"default_profile": true,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"muting": false
},
.....
.....
],
"next_cursor": 1489467234237774933,
"next_cursor_str": "1489467234237774933",
"previous_cursor": 0,
"previous_cursor_str": "0"
}
As you notice, the user object has a lot of properties, and I don't want to
parse them one by one or use a library to do that for me.
The TwitterKit has a class named TWTRUser, and here is it's documentation. To initialize an object of this class, you can just use a constructor that takes a JSON dictionary like this:
let follower = TWTRUser(jsonDictionary: jsonDictionary)
This way I can get the JSON Object the is returned to me parsed and initialize a TWTRUser object.
The problem is that TWTRUser doesn't have all the properties listed in the JSON returned, it only has these properties as listed in the documentation:
userID property
name property
screenName property
isVerified
property
isProtected property
profileImageURL property
profileImageMiniURL property
profileImageLargeURL property
formattedScreenName property
profileURL property
I tried to use valueForKey method that takes a key and returns it value like this:
let createdAt = follower.value(forKey: "created_at")
I thought it would work, but it didn't. When I use it the application crashes and gives me the following message:
Terminating app due to uncaught exception 'NSUnknownKeyException',
reason: '[ valueForUndefinedKey:]: this class
is not key value coding-compliant for the key contributors_enabled.'
What could I do to get all the user's properties using TWTRUser class?
value(forKey:) is a method inherited with NSObject and it is used for Key-Value Coding so it doesn't return results of the JSON. The TWTRUser class only defines 10 properties and that's all you can get with it. If you want to get other properties, you would have to parse the JSON yourself with the following line of code (using the standard library)
let user = try JSONSerialization.jsonObject(with: jsonDictionary) as? [String: Any]
First of all, like it's already been mentioned, don't use value(for key), if the object had that value it probably would expose it through a public property.
My suggestion would be to subclass TWTRUser, add the properties you want to your new class (you can call it something like TwitterUser) and override init(json), there you can see if the dictionary contains the values you want and add them to the object.
After that you'll be able to access those properties like you would with any other properties in the TWTRUser class.
I am struggling a little bit to use DDMathParser framework for expression requirement I have. I have JSON of fields & based on expressions certain fields can be set required, hidden or set the value of it.
Expressions in required tag in sample JSON are not fixed & so not getting how to achieve dynamic approach for expression.
[
{
"name": "firstName",
"value": "Ameer",
**"required": true**
},
{
"name": "lastName",
"value": "Shaikh",
**"required": "$firstName != ‘’"**
},
{
"name": "designation",
"value": "",
**"required": "$firstName == ‘Ameer’ && $lastName == ‘Shaikh’"**
},
{
"name": "location",
"value": "",
**"hidden": false**
}
]
Actually, expression in JSON contains $ to represent one of the
dictionary objects value from JSON. Wherein framework internally
treats it as a local variable.
These expressions may have different combinations as well. There may be several expression apart from "required" parameters. I need to run all relevant expressions for any change in value in UI.
EDIT
let expression = "$firstName == ‘Ameer’ && $lastName == ‘Shaikh’"
let dict = ["firstName": "Amir", "lastName": ""]
let e = try! Expression(string: expression)
let result = try! Evaluator.default.evaluate(e, substitutions: dict)
Though it should parse a correct value from JSON, I have hard coded substitutions string to at least get a breakthrough. Here, substitutions expect String & Double & give error as "Cannot convert a value of type [String: String] to expected arg type substitutions (Dcitionary).
Is there any way to pass String: String substitutions?
DDMathParser is not built to do string evaluations. It's technically possible to make it work, but it's a bit beyond the scope of the framework.
For this situation, I think you'd be better off using NSPredicate, which does allow string comparisons and variable substitutions.
In a JSON model coming from a REST api I have a field that is supposed to be a Dictionary (a map, hashtable, call it whatever you want), e.g.:
"moduleMap": {
"677e55b2-d80c-4b32-bcbb-e99074fbfcf6": {
"id": "677e55b2-d80c-4b32-bcbb-e99074fbfcf6",
"startTime": 1496054599227,
"status": "ACTIVE"
},
"c20acde2-639f-4cb7-9b90-6d8d24c78166": {
"id": "c20acde2-639f-4cb7-9b90-6d8d24c78166",
"startTime": 1496054598997,
"status": "UNAVAILABLE"
}
}
As I understand RestKit (I am a newbie), usually this is mapped to an object in Swift. However, since the keys in this map are arbitrary uuids, I cannot write a class with these properties.
Can anybody point me to a direction of how to get this map into a Swift dictionary using RestKit mapping?
I would like to map it to var moduleMap: [String:DomainObject], or at least var moduleMap: NSMutableDictionary. Also, I need it to be mappable back to the same JSON.
I have following REST API response:
"items":
[
{
"empid": "1234",
"name": "Santosh",
"hiredby": "Mark",
"date": "2017-01-31,00:19:41 PST",
},
{
"empid": "5678",
"name": "Kumar",
"hiredby": "Bob",
"date": "2017-01-31,08:30:31 PST"
}
]
My query is : - How do i get empid based on querying name as Kumar.
For example: I need to find "Kumar" name and get his empid. (that is, search by name and get his empid as response) I'm able to get the response and store it in Response object. but, from response object how can i traverse and query to get the required value.
Also,
I tried by retrieving as:
String name = get(REST_ENDPOINT).then().body("items.name",hasItems("Kumar")).extract().path("items.empid").toString();
when i print the response i get collection of the empid like [1234,5678], where as my expectation is to get only 5678.
Do I need to parse via JSONArray and JSONObject and iterate the response?
Please suggest.
You can use something like this
response1.jsonPath().getList("collect { it.credentials.findAll { it.credentialType == 'Ban User Name'}.credentialId }.flatten()")