While I was invited to sync my company and created an iPhone app, I was wondering how to pass values between the web server and the iPhone app. At that time, it seems that JSON is used to pass the value! I learned that. So, as a result of various investigations, I was able to pass the value using JSON safely, so I will summarize it.
I am writing with the knowledge gained from new employee training & self-learning, so if there is something wrong or a better way, please comment ...
The screen looks like this.
The flow is like this. ① Click the "Get JSON" button and pass a random number to JavaServlet. (2) JavaServlet responds with JSON according to the received numerical value. ③ Swift converts the received JSON object and outputs the value to the screen.
The JSON obtained from JavaServlet is output in the part surrounded by the red frame. Also, implement everything in the local environment.
Developed using Xcode and Eclipse. When using JSON, I was at a loss with GSON or Jackson, but this time I used Jackson. I referred to the following for how to set up Jackson in Eclipse. https://tech.pjin.jp/blog/2020/03/09/jackson_setup/
Xcode Screen to get JSON
ViewController.swift
import UIKit
class ViewController: UIViewController {
//Display wording
var textId = ""
var textName = ""
//Declaration of tuple array
var studentList:[(id:String , name:String)] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func getJson(_ sender: Any) {
self.performSegue(withIdentifier: "goResultVC", sender: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//Request URL Specify a servlet that returns JSON
guard let req_url = URL(string: "http://localhost:8080/servlet_test/JsonServlet")
else{return}
//Generate the information required for the request
var req = URLRequest(url: req_url)
//0~Get a random number of 2
let id = Int.random(in: 0...2)
//Create a session to manage data transfers
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
//Set the information (ID) to be passed to JavaServlet in Body
req.httpMethod = "POST"
req.httpBody = "id=\(id)".data(using: .utf8)
//Register request as a task
let task = session.dataTask(with: req, completionHandler: {
(data, response ,error) in
//End of session
session.finishTasksAndInvalidate()
do{
//Convert the retrieved JSON
let decoder = JSONDecoder()
let json = try decoder.decode(StudentJson.self, from: data!)
self.textId = json.id!
self.textName = json.name!
//Segue linked to the "Get JSON" button
if segue.identifier == "goResultVC" {
let nextVC = segue.destination as! ResultViewVontroller
nextVC.jsonId = self.textId
nextVC.jsonName = self.textName
}
}catch{
print(error)
print("I got an error")
}
})
//Download started
task.resume()
}
//JSON data structure
struct StudentJson: Codable {
let id: String?
let name: String?
}
}
Screen to output JSON
ResultViewVontroller.swift
import UIKit
class ResultViewVontroller: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//Output message field
var jsonId = ""
var jsonName = ""
//Output label
@IBOutlet weak var resultJsonId: UILabel!
@IBOutlet weak var resultJsonName: UILabel!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
resultJsonId.text = jsonId
resultJsonName.text = jsonName
}
}
Eclipse
Java Servlet
JsonServlet.java
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import bean.JsonBean;
/**
* Servlet implementation class JsonServlet
*/
@WebServlet("/JsonServlet")
public class JsonServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public JsonServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
JsonBean jsonBeanList[] = new JsonBean[3];
//Set a value in a Java object
JsonBean jsonBean = new JsonBean();
jsonBean.setId("101");
jsonBean.setName("tanaka");
JsonBean jsonBean2 = new JsonBean();
jsonBean2.setId("102");
jsonBean2.setName("yamada");
JsonBean jsonBean3 = new JsonBean();
jsonBean3.setId("103");
jsonBean3.setName("satou");
jsonBeanList[0] = jsonBean;
jsonBeanList[1] = jsonBean2;
jsonBeanList[2] = jsonBean3;
//
String str = request.getParameter("id");
int requestId = Integer.parseInt(str);
System.out.println(requestId);
ObjectMapper mapper = new ObjectMapper();
try {
//Convert from Java object to JSON
String testJson = mapper.writeValueAsString(jsonBeanList[requestId]);
//JSON output
response.getWriter().write(testJson);
//Check the output JSON
System.out.println(testJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
Bean
JsonBean.java
package bean;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class JsonBean {
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
To see how JsonServlet works, we recommend the Talend API Tester, a Chrome extension! Talend API Tester
You can now communicate between the front end and the back end. Next, let's get on AWS.
In addition, I referred to many Qiita articles and books for this implementation.
It was a poor content, but thank you for reading!
Markdown notation is really easy to write.
Recommended Posts