[SWIFT] Try passing values from Java Servlet to iPhone app using JSON

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 ...

App to create

The screen looks like this. スクリーンショット 2020-05-12 22.47.32.png

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.

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/

Actual code

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

Summary

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

Try passing values from Java Servlet to iPhone app using JSON
Java: How to send values from Servlet to Servlet
[Java] Try to implement using generics
Try accessing the dataset from Java using JZOS
Ssh connect using SSHJ from a Java 6 app
Try to access the on-premise system from SAP Cloud Platform --Java App Edition
Convert Java enum enums and JSON to and from Jackson
Changes from Java 8 to Java 11
Sum from Java_1 to 100
From Java to Ruby !!
Generate models from JSON to Swift, PHP, C #, JAVA
Try to build a Java development environment using Docker
[Java] Try editing the elements of the Json string using the library
Try Spark Submit to EMR using AWS SDK for Java
Try using RocksDB in Java
Migration from Cobol to JAVA
Try scraping using java [Notes]
Try using Cocoa from Ruby
New features from Java7 to Java8
Connect from Java to PostgreSQL
Using Docker from Java Gradle
From Ineffective Java to Effective Java
[Java] Try to solve the Fizz Buzz problem using recursive processing
[Android] Convert Map to JSON using GSON in Kotlin and Java
Passing parameters from JSP with Servlet
Try using Redis with Java (jar)
Java to be involved from today
From Java to VB.NET-Writing Contrast Memo-
Java, interface to start from beginner
Try to create a server-client app
Try to implement Yubaba in Java
Try using IBM Java method tracing
The road from JavaScript to Java
[Java] Conversion from array to List
Sample code using Minio from Java
Try using Hyperledger Iroha's Java SDK
[Java] Where did you try using java?
Try to issue or get a card from Jave to Trello using API
Try to get data from database using MyBatis in Micronaut + Kotlin project