What is the best way to convert a JSON string received from Angular into a Java Object within a Spring

I am currently utilizing WebSocket to create a chat application.

Below is the code from my Angular application that sends a MessageModel object to the backend after converting it into a JSON string:

sendMessage(message: MessageModel){
let data = JSON.stringify({
  message: message
})    
this.ws.send("/messaging/"+message.receiverId, {}, data); }

Here is the Java code responsible for receiving the message:

@MessageMapping("/messaging/{to}")
@SendTo("/inbox/coversation/{to}")
public String processMessageFromClient(@DestinationVariable String to, @Payload String message) throws Exception {
    MessageModel msg = new MessageModel();
    System.out.println(message);

    msg = new Gson().fromJson(message, MessageModel.class);
    System.out.println(msg);

    return message;
}

The output of System.out.println(message) shows:

{"message":{"messageText":"hey","senderId":4,"senderName":"Akash Malhotra","receiverId":1,"senderEmail":"[email protected]","sentTime":"15:19:43 GMT+0530 (India Standard Time)","date":"08/06/2020, 15:19:43"}}

and

The output of System.out.println(msg) displays:

MessageModel [messageText=null, senderName=null, senderId=null, senderEmail=null, profilePicUrl=null, receiverId=null, sentTime=null, date=null]

QUERY: I am seeking help on how to properly set the 'String message' received from Angular into my MessageModel object in Java as it currently shows all null values.

Answer №1

Summary: Success!

public class ProblemSolved
{
    public String analyzeClientMessage( String recipient, String text ) throws Exception
    {
        System.out.println( text );

        final MessagePack pack = new Gson().fromJson( text, MessagePack.class );
        System.out.println( pack.text );

        return text;
    }

    public static void main( String[] args ) throws Exception
    {
        final String jsonData = "{\"text\":{\"messageText\":\"hello\",\"senderId\":4,\"senderName\":\"John Doe\",\"receiverId\":1,\"senderEmail\":\"john.doe@example.com\",\"sentTime\":\"15:19:43 GMT+0530 (India Standard Time)\",\"date\":\"08/06/2020, 15:19:43\"}}";
        new ProblemSolved().analyzeClientMessage( "Me", jsonData );
    }
}

class MessageData
{
    String messageText;
    String senderName;
    Integer senderId;
    String senderEmail;
    String profilePicUrl;
    Integer receiverId;
    String sentTime;
    String date;

    @Override
    public String toString()
    {
        // ... etc.
    }
}

class MessagePack
{
    MessageData text;
}

Detailed Explanation:

The provided JSON string includes an inner layer wrapped as follows:

{
    "text" = { /* properties of MessageData */ }
}

As the MessageData structure lacks a text field, the values are not assigned and end up as null. By encapsulating MessageData inside another class called MessagePack that contains a text field of type MessageData, GSON can effectively parse the contents of the MessageData.

Answer №2

To enhance your method, pass MessageModel instead of a String as an argument. Spring will utilize the underlying jackson (or a specific mapper you have configured for Spring) to convert the payload into a MessageModel object through the designated MessageModel class.

@MessageMapping("/messaging/{to}")
@SendTo("/inbox/conversation/{to}")
public String processMessageFromClient(@DestinationVariable String to, @Payload MessageModel message) throws Exception {
    ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using a Typescript typeguard to validate function parameters of type any[]

Is it logical to use this type of typeguard check in a function like the following: Foo(value: any[]) { if (value instanceof Array) { Console.log('having an array') } } Given that the parameter is defined as an array o ...

Angular's ng-model is unable to access the value of an object array

When selecting the days, users should be able to input check-in and check-out time ranges dynamically. However, there seems to be an issue with retrieving the values and data format. The ng model is unable to capture the check-in and check-out values. The ...

Creating a Clojure package for improved functionality

Attempting to use the hierarchical-classifier.clj script from GitHub, I encountered an issue when trying to modify the path within *directory-string* to point to my Dropbox directory containing text files. The REPL threw a compiler exception for org.apache ...

I want to create a feature where a video will automatically play when a user clicks on a specific item in a list using Angular

Currently, I'm working on a project that involves displaying a list of videos and allowing users to play them in their browser upon clicking. The technology stack being used is Angular 2. Below is the HTML code snippet for achieving this functionalit ...

How to declare multiple components in @ngModule using Angular 2

Currently, I'm working on a hefty project that combines Angular 2 with ASP.net MVC. I've got around 120 components declared within the @NgModule block like so: @NgModule({ imports: [CommonModule], declarations: [Component1, Component2, Comp ...

Issue with Angular project: View not being updated when using behaviorSubjects

Within my Angular project, I am retrieving data from an API using a service and storing the data within a BehaviorSubject as shown below private categorySubject = new BehaviorSubject<number | null>(null); apiBehavior = new ReplaySubject<ApiRes ...

Get the final element with a for loop in Angular 2

I am currently utilizing angular 2 in conjunction with mongoDb. The service I am employing is responsible for calling the API. Here is a snippet of my code: this.at represents a token, similar to fdfdsfdffsdf... This token serves as an authorization key ...

The header remains unchanged even after verifying the user's login status

Currently, I am using Angular 11 for the front-end and Express for the back-end. I am facing an issue with determining if a user is logged in so that I can display the correct header. Even after logging in and setting a cookie in the browser upon redirecti ...

Show a dropdown menu based on a certain condition in Angular

Is there a way to conditionally display select options like this? <select id="updateType" class="form-control" formControlName="updateType"> <option value="personalDetails">Personal</option> <option value="addressD ...

Guide to formatting JSON correctly in Java

private List<String> itemsInCart = new ArrayList<>(); private List<String> itemObjectsInCart = new ArrayList<>(); @CrossOrigin @GetMapping(value = "/cartitems") public List<String> getItemsInCart(@RequestParam("buyerId") Int ...

Navigate to the editing page with Thymeleaf in the spring framework, where the model attribute is passed

My goal is to redirect the request to the edit page if the server response status is failed. The updated code below provides more clarity with changed variable names and IDs for security reasons. Controller: @Controller @RequestMapping("abc") public clas ...

Centered title in side menu for Ionic 3

I recently utilized the Ionic CLI to create an Ionic project. The version I am working with is Ionic 3. Currently, I am facing a challenge in centering the title image. Any assistance on this matter would be greatly appreciated. <ion-menu [content]=" ...

What is the most effective way to sort a list using Angular2 pipes?

I'm currently working with TypeScript and Angular2. I've developed a custom pipe to filter a list of results, but now I need to figure out how to sort that list alphabetically or in some other specific way. Can anyone provide guidance on how to a ...

Assets failing to duplicate during ng build in production

Currently, I'm developing an application using Angular 4. I recently added a new SVG image to the assets/images folder and made the necessary changes in the angular-cli.json file as well. When I run 'ng build' locally, it successfully copies ...

Challenges with Typescript Integration in Visual Studio 2013

Currently diving into typescript as a newbie while going through the Angular tutorial using Visual Studio 2013 for work, which is also new to me. The frustrating part is that Visual Studio seems to be assuming I am going to use a different language (judgin ...

Navigating through table rows using Selenium WebDriver

Encountering a problem with Selenium in Java. The webpage structure is as follows: <html> <body> <div id='content'> <table class='matches'> <tr id='today_01'> <td class='team-a'> ...

Converting a JAXB XML file into a JSON format

After generating an XML dump file using JAXB and applying multiple transformations, I finally obtain an XML file in the desired format. Now, my goal is to convert this properly escaped and encoded XML file into a JSON file with the help of JAXB. I want to ...

Employing async await for postponing the execution of a code block

I have been working on an Angular component where I need to perform some actions after a data service method returns some data asynchronously. Although I attempted to use async/await in my code, I feel that I may not have fully understood how it works. Her ...

Material Design Autocomplete search feature in Angular 2

I'm encountering some challenges with autocomplete in Angular2 Material Design. Here are the issues I'm facing: 1. When I type a character that matches what I'm searching for, it doesn't display in the autocomplete dropdown as shown in ...

"Troubleshooting: Why is the Angular Material MatPaginator not showing any

I'm facing an issue while trying to set up a data table in Angular 8. The paginator located below the data table seems to be malfunctioning. Despite having 10 hardcoded records in my component, changing the elements per page to 5/10 does not alter the ...