DEV Community

Cover image for How to pass Multiple Data Types from Angular to Spring RESTful web services
lou
lou

Posted on • Updated on

How to pass Multiple Data Types from Angular to Spring RESTful web services

Client side :

To communicate with a server over HTTP. Angular makes requests and receive responses using HttpClient and the data comes in the format of JSON by default.

JSON (JavaScript Object Notation) is a format for data sent to and from APIs.

Consider we have a JavaScript object student and a number idD for example.
We want to send both the object and the number to the server side.

To do this, first create an object with these 2 elements

{student: student, idD: idD}

Now convert the object into a JSON string using JSON.stringify()

Our code is going to look like this:

public saveStudent(student : Student, idD:number):Observable<Object>{
    var data=JSON.stringify({student: student, idD: idD})
    return this.http.post<Object>(environment.backendHost+"/admin/students" ,data );
  }

Enter fullscreen mode Exit fullscreen mode

Now your data is going to be sent to the server as a string.

Server side:

First Add the following dependencies to your POM.XML file:

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20220320</version>
        </dependency>
Enter fullscreen mode Exit fullscreen mode
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.1</version>
        </dependency>
Enter fullscreen mode Exit fullscreen mode

Remember that we sent a String from the client side to the server side.

Your controller class should be expecting a String

@PostMapping(value = "/admin/students")
    public Student saveStudent(@RequestBody String myObject ) {
Enter fullscreen mode Exit fullscreen mode

To convert the String to a JSON Object, we will be using JSONObject which is a subclass of java.util.HashMap.

First we need an implementation of a JSON package in Java.

Github repository:

GitHub logo stleary / JSON-java

A reference implementation of a JSON package in Java.

Json-Java logo

image credit: Ismael Pérez Ortiz

JSON in Java [package org.json]

Maven Central Java CI with Maven CodeQL

Click here if you just want the latest release jar file.

Overview

JSON is a light-weight language-independent data interchange format.

The JSON-Java package is a reference implementation that demonstrates how to parse JSON documents into Java objects and how to generate new JSON documents from the Java classes.

Project goals include:

  • Reliable and consistent results
  • Adherence to the JSON specification
  • Easy to build, use, and include in other projects
  • No external dependencies
  • Fast execution and low memory footprint
  • Maintain backward compatibility
  • Designed and tested to use on Java versions 1.6 - 21

The files in this package implement JSON encoders and decoders. The package can also convert between JSON and XML, HTTP headers, Cookies, and CDL.

If you would like to contribute to this project

For more information on contributions, please see CONTRIBUTING.md

Bug fixes, code improvements, and unit test…

Import the following in your Rest Controller:

import org.json.JSONObject;

Enter fullscreen mode Exit fullscreen mode

Inside your controller pass you object as a parameter to the JSONObject's constructor

JSONObject jsonObject = new JSONObject(myObject);

Enter fullscreen mode Exit fullscreen mode

In this example we're going to be using two JSONObject methods:
getJSONObject(String name)

That returns the object value to which the specified name is mapped.
And

getInt(String name)

That returns an integer from JSON number.

JSONObject myobj = jsonObject.getJSONObject("student");
int idD= jsonObject.getInt("idD");

Enter fullscreen mode Exit fullscreen mode

The last step is to transform JSON object into a Java Object

I'm going to be using Gson which is a Java library that is used to serialize and deserialize Java objects to JSON

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Github repository:

GitHub logo google / gson

A Java serialization/deserialization library to convert Java Objects into JSON and back

Gson

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.

Note

Gson is currently in maintenance mode; existing bugs will be fixed, but large new features will likely not be added. If you want to add a new feature, please first search for existing GitHub issues, or create…

Create a Gson object using the constructor:

Gson gson= new Gson();

Enter fullscreen mode Exit fullscreen mode

In this example we're going to be using the fromJson() method

fromJson(java.lang.String json, java.lang.reflect.Type typeOfT)

Enter fullscreen mode Exit fullscreen mode

This method deserializes the specified Json into an object of the specified type.

Convert your JSONObject myobj into a string using toString()

Then pass it as the first parameter to the fromJson() method.
The second parameter is going to be your java class.

Student student = gson.fromJson(myobj.toString(),Student.class);

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
nermin_karapandzic profile image
Nermin Karapandzic

A better practice would be to create a DTO class which would represent that request, use that class as request body and let Jackson do the deserialization, no need for complicating, at least for the given example.