How to change JSON key name Swift? - ios

In my application I have used the same keyname to get data everywhere, now in json response that data is same but in one place the keyname is changed so I want to rename the keyname of the array in my json this is what I am getting searched on stack overflow but unable to find any reliable way please guide me any good way to do it
{"status":"success","msg":"deleted","pro_data":[]}
I want JSON with these keys:
{"status":"success","msg":"deleted","Images":[]}

you can use Codable to create JSON model and in that you can customise you key.
I assume your JSON response ({"status":"success","msg":"deleted","pro_data":[]}) available in Data format.
So, See the following code which are used to create JSON model for your data.
struct WSModel: Codable {
var status : String?
var msg : Int?
var Images : [Any]?
enum CodingKeys: String, CodingKey {
case currentPage = "status"
case msg = "msg"
case Images = "pro_data"
}
}
Due to there aren't any data type inside your array I have keep Any type of data.This code is work for when keys in response are "status", "msg", "pro_data".
Try this code and let me know still an issue. I hope this will work for you.

I assume your issue is that you want to continue to use "Images":[] key, without having to change rest of your code.
In your JSON response that you want to change, you can try something like this.
response["Images"] = response["pro_data"]

Related

Nestjs swagger array of strings with one parameter

When I send only one parameter, I got query result like string, not like string[]. This heppend only from UI swagger, if I send from Postman - it works good.
I just want send from swagger-ui one parammeter and got array of string, not string
How I can fix it? Help me please.
Example1: send one paramenter and in my controller I got string like '25'
Example2: when I send 2 parameters in controller I can see array of strings ('25', '21')
export class List {
#ApiProperty({ isArray: true, type: String, required: false })
#IsOptional()
public categories?: string[];
}
You should try to spread your parameter in a const in services
edit:
I don't know how to explain in formal words, but a array of strings of one item, for JAVASCRIPT, seems with the same thing as one string value.
Because array is not a type, but a form of a type....
So, if you, in your controller, before do anything with it, you redeclare as:
#Get(":id")
findManybyId(#Param("id") id: string[]) {
const idArray = [...id];
return await this.service.findManyById(idArray);
}
It will solve your problem about being an array
old answer:
You should try to change in your controller where you make your input decorator.
in your case, i don't know if you are using ID to get, but you must to do as the example:
#ApiOperation({
summary: "Get many categories by ID",
})
async getMany(
#Param("id") ids: string[],
) {
return await this.categoriesService.getMany(id);
}
when you fill a single category the query param will be translated as a string while when you fill in several categories understand it as a array.
to solve this problem I added in DTO :
#Transform(({ value }) => (Array.isArray(value) ? value : Array(value)))
I force the cast to array

How to get a response key into the URL, Google Apps Script

I need to get the permission to access to specific URL, but before that I need to get the responseKey, and the way to get the responseKey is to access to this URL in the browser: https://api.getgo.com/oauth/v2/authorize?client_id={consumerKey}&response_type=code. After accessing
it contains the responseKey what I need. It will look something like: http://example.com/oauthreturn/?code={responseKey}. The question is how I can get the responseKey in code in google-apps-scrpits.
This what i wrote:
function myFunction() {
var client_id='xxxxxxxxxxxxxxxxx'
var url ="https://api.getgo.com/oauth/v2/authorize?client_id="+client_id+"&response_type=code";
var resp = UrlFetchApp.fetch(url)
}
but I get a HTML code response
In your code var resp = UrlFetchApp.fetch(url) will create a HTTPResponse object. First, you will want to know if the response code is 200 OK. To gather that information you should use getResponseCode() and check if it equals to 200. If that is the case, then you must parse the code. To do that you can first use getContentText() and after that parse(). One example implementation, that is compatible with your code, can be this one:
if (resp.getResponseCode() == 200) {
var results = JSON.parse(resp.getContentText());
}
You can then access to the data referring to that variable and the name of the parameter. For example, you could use results.code, results.token… If this explanation doesn't clarify your question, please ask me again for further help.

How to send [String:Any] dictionary in multipart API?

I am trying to send multipart image data using Alamofire with [String:Any] parameters ,i am only able to to post [String:String] parameters only
For [String:String] is doing like https://stackoverflow.com/a/40440371/4466607
but now i have to post like :
[ PayLoad ] and i have to send Image with image key which, i am already doing .
In postman it is working fine
Question :
How can i post image with Dictionary type [String:Any] in Swift
Please help
If your value is Any type then check this may be it helps you.
for (key, value) in params {
let paramsData:Data = NSKeyedArchiver.archivedData(withRootObject: value)
formData.append(paramsData, withName: key)
}
Rough solution:
If you insist on put Image data into a dictionary, you could convert image data to Base64 code, and then put Base64 string in the dictionary. You will submit a big JSON to the server. I don't think it's a good solution.
Better solution:
Another WebApi to submit images data, and that API will return uploaded images URL like https://www.example.com/image1234.jpg, or just return image id like "1234" which can be embedded to a URL lately. Finally, you submit the JSON data with image URL or id like {"image":"https://www.example.com/image1234.jpg"} or {"image":1234}.

Does a iOS post request has to look same as what rest api expects?

I have to send a JSON file that I collect on my iOS to my backend team. The JSON looks something like:
{
"samples" : [
{
"acw" : 11,
"e_reserved" : 0,
"acc" : 28,
"cheat_rate" : 16,
}
]
}
I am making a post request to backend at:
http://make-post.com/api/post-activities
The backend expects the JSON as:
/api/post-activities/
Request Body
The request body should be a "application/json" encoded object,
containing the following items.
Parameter Description
name
time_stamp
duration
We do not collect all these data ourselves but backend has to process the data we supply and get those info.
What I tried first was to put all these data in an online storage and create a request as:
Request: {“pod_id”:“F11”,“type”:“Normal Activity”,“time_stamp”:“2019-04-17T22:29:35.147Z”,“url”:“https:\/\/s3.amazonaws.com\/mybucket-test\/myid#gmail.com\/2019-04-17\/d9335.json”}
But when I send request like this, I get Status Code 400 error.
So my next idea was to pass the whole JSON I collect to them. Upon doing that, they can get the data and see it in there database even though I get 500 error. Does it mean it is not really working?
The question is unclear to me, The learnings I have learnt you have some data that you want to pass to backend, and the backend sends 400 as you are not meeting his desire.
Suppose you have three variables to pass , let name,time_stamp, duration.
All you need to do in Swift, use Codable protocol.
class postJSON : Codable {
var name : String?
var time_stamp : String? // it may be Int64 according to backend what accept
var duration : String? // it may be Int64 according to backend what accept
}
While making a post request just do
let encodedData = try? JSONEncoder().encode(postJSON)

How do I create a Siesta transformer for an API endpoint that contains a JSON array?

I'm building an app that needs to make a GET request to the API endpoint https://thecountedapi.com/api/counted using the Siesta framework. The endpoint returns a JSON array, just like an endpoint like https://api.github.com/users/ebelinski/repos, which is used in the Siesta example Github Browser. As a result, I'm trying to make my app use Siesta in the say way that one does. I create a service:
let API = Service(baseURL: "https://thecountedapi.com/api")
Then a transformer for my endpoint in application:didFinishLaunchingWithOptions:
API.configureTransformer("/counted") {
($0.content as JSON).arrayValue.map(Incident.init)
}
Where Incident is a struct with an initializer that takes in a JSON object.
Then in my view controller, I create a resource:
let resource = API.resource("/counted")
and in viewDidLoad:
resource.addObserver(self)
and in viewWillAppear:
resource.loadIfNeeded()
Then I have the following function in my VC to listen to changes:
func resourceChanged(resource: Resource, event: ResourceEvent) {
print(resource.jsonArray)
if let error = resource.latestError {
print(error.userMessage)
return
}
if let content: [Incident] = resource.typedContent() {
print("content exists")
incidents = content
}
print(incidents.count)
}
But when I run my app, I get mixed results. print(resource.jsonArray) just prints [], I have an error message Cannot parse server response, and if I set Siesta.enabledLogCategories = LogCategory.detailed, I can see the error mesage [Siesta:StateChanges] Siesta.Resource(https://thecountedapi.com/api/counted)[] received error: Error(userMessage: "Cannot parse server response", httpStatusCode: nil, entity: nil, cause: Optional(Siesta.Error.Cause.WrongTypeInTranformerPipeline(expectedType: "JSON", actualType: "__NSCFArray", transformer: Siesta.ResponseContentTransformer<SwiftyJSON.JSON, Swift.Array<TheCountedViewer.Incident….
If I comment out the whole transformer, I have some success in that print(resource.jsonArray) prints out the correct array from the endpoint. So my transformer must be wrong in some way, but I think I'm using basically the same transformer as in Github Browser:
service.configureTransformer("/users/*/repos") {
($0.content as JSON).arrayValue.map(Repository.init)
}
Am I missing something?
The key clue to your problem is buried in that (perhaps not ideally helfpul) log message:
Siesta.Error.Cause.WrongTypeInTranformerPipeline
expectedType: "JSON"
actualType: "__NSCFArray"
It’s saying that your transformer expected an input type of JSON, which makes sense — you said as much with ($0.content as JSON). However, it got the type __NSCFArray, which is the secret internal backing type for NSArray. In other words, it expected a SwiftyJSON value, but it got the raw output of NSJSONSerialization instead.
Why? The GithubBrowser project includes an NSDict/NSArray → SwiftyJSON transformer which it configures in the parsing stage. The model transformers in that project all depend on it.
To use SwiftyJSON in the same way in your project, you’ll need to include that transformer from the example project in yours:
private let SwiftyJSONTransformer =
ResponseContentTransformer
{ JSON($0.content as AnyObject) }
And then when setting up your service:
service.configure {
$0.config.pipeline[.parsing].add(SwiftyJSONTransformer, contentTypes: ["*/json"])
}
(Note that you might want to create the ResponseContentTransformer with transformErrors: true if you are interested in errors.)
An alternative way to use SwiftyJSON, which is not quite as pretty but requires less setup, is to manually wrap things in JSON in each individual response transformer:
service.configureTransformer("/users/*/repos") {
JSON($0.content as AnyObject).arrayValue.map(Incident.init)
}

Resources