Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Friday, 8 November 2024

Amazon SQS Java: Send and Receive Product Objects | Amazon SQS: Sending and Receiving Custom Objects

🚀 Master AWS Development with Java!

Subscribe to Ram N Java for more hands-on tutorials on AWS SDK and Java integration.

SUBSCRIBE TO THE CHANNEL

Introduction

Amazon Simple Queue Service (SQS) is a fundamental tool for building decoupled, distributed systems. While SQS natively handles strings, most real-world applications need to exchange complex data. In this tutorial, we demonstrate how to use the AWS SDK for Java and Jackson to send and receive custom Product objects by serializing them into JSON.

Step 1: Maven Dependencies

To follow along, ensure your pom.xml includes the AWS SDK for SQS and the Jackson library for JSON processing:

<!-- AWS SDK for SQS -->
<dependency>
    <groupId>software.amazon.awssdk</groupId>
    <artifactId>sqs</artifactId>
    <version>2.x.x</version>
</dependency>

<!-- Jackson for JSON -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

Step 2: Defining the Product Class

Create a simple POJO to represent your data. This class should have a default constructor and standard getters/setters for Jackson to work correctly.

public class Product {
    private int id;
    private String name;
    private double price;
    // Getters and Setters
}

Step 3: The Producer (Sending Objects)

The producer converts the Java object to a JSON string using ObjectMapper and sends it to the SQS queue using the SendMessageRequest.

ObjectMapper mapper = new ObjectMapper();
String productJson = mapper.writeValueAsString(new Product(1, "iPhone 16 Pro Max", 125000));

SendMessageRequest sendMsgRequest = SendMessageRequest.builder()
    .queueUrl(queueUrl)
    .messageBody(productJson)
    .build();
sqsClient.sendMessage(sendMsgRequest);

Step 4: The Consumer (Receiving Objects)

The consumer receives the message, extracts the JSON body, and deserializes it back into a Product object. Don't forget to delete the message after successful processing!

ReceiveMessageResponse response = sqsClient.receiveMessage(receiveRequest);
for (Message message : response.messages()) {
    Product product = mapper.readValue(message.body(), Product.class);
    System.out.println("Processing: " + product.getName());
    
    // Delete message from queue
    DeleteMessageRequest deleteRequest = DeleteMessageRequest.builder()
        .queueUrl(queueUrl)
        .receiptHandle(message.receiptHandle())
        .build();
    sqsClient.deleteMessage(deleteRequest);
}

Conclusion

By combining the AWS SDK with Jackson, you can easily pass complex data structures through Amazon SQS. This pattern is essential for microservices architectures where different components need to exchange typed data asynchronously. Happy coding!

Friday, 27 January 2023

SpringBoot - Send/Consume Custom Object into/from Apache Kafka Server running on Amazon EC2 Instance

🚀 Master Spring Boot & Kafka!

Subscribe to Ram N Java for simplified tutorials on Spring Boot, Apache Kafka, and Cloud Integration!

SUBSCRIBE TO OUR CHANNEL

Spring Boot & Kafka: Streaming Custom JSON Objects

Integration between Spring Boot and Apache Kafka is a cornerstone of modern backend engineering. In this tutorial, we "simplify" the process of sending and consuming Custom JSON Objects using a Kafka Cluster running on Amazon EC2.

The Spring Boot Workflow

We walk through the end-to-end technical setup required to handle complex data structures seamlessly:

  • Project Setup: Configuring pom.xml with the necessary Spring Kafka and Web dependencies.
  • Producer Configuration: Setting up the KafkaTemplate and ProducerFactory to handle custom Java objects (like an Animal class).
  • Consumer Implementation: Using @KafkaListener and ConcurrentKafkaListenerContainerFactory to receive and process JSON payloads.
  • REST API Integration: Creating a controller to trigger message production via Postman.

Connecting to the Cloud

For Java Developers, deploying to AWS EC2 adds a layer of real-world complexity. We demonstrate how to configure advertised.listeners in your Kafka server.properties and adjust AWS security groups to allow traffic on port 8082. This ensures your local Spring Boot producer and consumer can talk to the cloud cluster without issues.

Practical JSON Serialization

Understanding how to map Java POJOs to JSON for Kafka topics is critical. This guide provides the conceptual clarity and the actual code to make your Event-Driven Microservices robust. Join us at Ram N Java and master the art of Spring Boot Kafka integration.

📥 Build Your Pipeline!

Watch the full video to see the live demonstration and code walkthrough. Subscribe to Ram N Java for more high-quality tech guides and simplified backend tutorials!

Thursday, 19 January 2023

Spring Boot – Send Custom Object into Kafka Topic & Consume Custom Object From Kafka Topic

🚀 Simplify Your Spring Boot Kafka!

Subscribe to Ram N Java for simplified tutorials on Spring Boot, Apache Kafka, and Full-Stack Development!

SUBSCRIBE TO OUR CHANNEL

Spring Boot & Kafka: Sending and Consuming JSON Objects

Managing complex data between microservices is a breeze with Spring Boot and Kafka. In this tutorial, we "simplify" the process of Sending and Consuming Custom JSON Objects through a complete end-to-end example.

The End-to-End Pipeline

We walk through two separate Spring Boot applications—a producer and a consumer—to demonstrate the data flow:

  • Producer Setup: Configuring KafkaTemplate to handle custom Java objects (like our Animal class) and publishing them via a REST endpoint.
  • Consumer Setup: Implementing @KafkaListener with a ConcurrentKafkaListenerContainerFactory to seamlessly receive and process JSON payloads.
  • Object Mapping: Ensuring the Animal class structure and package names match on both sides for successful deserialization.
  • REST Testing: Using Postman to send JSON data (e.g., Lion, Cat details) to the producer and watching it appear in the consumer logs.

Why This Matters for Developers

For Java Developers and Backend Architects, mastering object-based streaming is essential for building Event-Driven Architectures. We show you how to use Spring Kafka's built-in support for JSON Serialization, removing the need for manual byte array conversions. This guide provides the practical technical clarity needed to scale your Microservices efficiently.

Clear Logic, Practical Results

See the code in action across two Eclipse instances, from zookeeper startup to live log monitoring. This tutorial gives you a ready-to-use template for handling any domain object in your Kafka cluster. Join us at Ram N Java and elevate your Spring Boot and Kafka expertise today.

📥 Start Your Project!

Watch the full video to see the step-by-step implementation and REST testing. Subscribe to Ram N Java for more high-quality tech guides and simplified backend tutorials!

Friday, 23 April 2021

Reading HTTP POST Request Body using @RequestBody annotation - RESTful Web Services with Spring Boot

🚀 Simplify Your API Logic!

Subscribe to Ram N Java for simplified Java, Spring Boot, and RESTful tutorials!

SUBSCRIBE TO OUR CHANNEL

Mastering the @RequestBody Annotation

How does Spring Boot magically convert raw JSON or XML from a request into a Java object? In this tutorial, we "simplify" the use of the @RequestBody annotation in Spring Boot to handle incoming data for your RESTful Web Services.

Inside the Request Body Flow

We walk through a practical example using an Employee model to show how Spring manages data transformation seamlessly:

  • @RequestBody Logic: See how this annotation instructs Spring to deserialize the inbound HTTP request body into your Java POJO.
  • Multi-Format Support: Learn how the same endpoint can consume and produce both JSON and XML payloads.
  • Content Negotiation: Mastering the Accept and Content-Type headers to control exactly what format your API returns.

Live Testing with Postman

We demonstrate real-time debugging, showing how a JSON payload is mapped to an object, modified with a random ID, and sent back to the client. You'll also learn how to toggle between JSON and XML responses by simply changing your request headers.

Why This is Essential

Understanding @RequestBody is fundamental for building any data-driven API. It allows you to create flexible, modern backends that can communicate with a variety of frontend clients, regardless of their preferred data format. Mastering this simplifies your controller logic and speeds up your development process.

📥 Download Java Source Code!

The full Java source code for this tutorial is available! You can find the direct download links in the YouTube video description above.

Returning Object as JSON or XML Representation - RESTful Web Services with Spring Boot

🚀 Build Versatile APIs!

Subscribe to Ram N Java for simplified Java, Spring Boot, and REST API tutorials!

SUBSCRIBE TO OUR CHANNEL

JSON or XML? Mastering Content Negotiation

Why choose between JSON and XML when your API can support both? In this tutorial, we dive into Content Negotiation in Spring Boot, allowing your RESTful Web Services to serve data in the format your clients prefer.

How Content Negotiation Works

By default, Spring Boot favors JSON, but with a few simple configurations, you can enable XML support. We explore the core components that make this possible:

  • The Jackson Dataformat XML Dependency: Learn which library you need to add to your pom.xml to unlock XML support.
  • The Accept Header: See how clients use this HTTP header to tell the server exactly which format they want to receive.
  • Automatic Transformation: Understand how Spring Boot's Message Converters automatically switch between formats based on the request.

Live Testing with Postman

We demonstrate the power of flexibility by testing the same endpoint with different headers. You'll see how changing the Accept header from application/json to application/xml instantly transforms the response format without changing a single line of Java code!

The Professional Advantage

Building "Content-Type aware" APIs is a mark of a professional developer. It makes your microservices more compatible with legacy systems that might still rely on XML, while staying perfectly modern for JSON-based frontend applications. Mastering this in Spring Boot ensures your backend is ready for any integration challenge.

📥 Download Slides & Source Code!

The complete source code and PowerPoint presentation for this content negotiation tutorial are available for download! Check out the direct links in the YouTube video description.

Returning Java Object as Return Value - RESTful Web Services with Spring framework | Spring Boot

🚀 Build Modern APIs!

Subscribe to Ram N Java for simplified Java, Spring Boot, and REST API tutorials!

SUBSCRIBE TO OUR CHANNEL

Returning Java Objects in REST APIs

In this tutorial, we explore the core of RESTful Web Services: returning Java objects as JSON responses. We demonstrate how Spring Boot seamlessly handles data serialization, making it incredibly easy to build data-driven applications.

The Magic of Serialization

Spring Boot uses the Jackson library under the hood to convert your Java POJOs into JSON. We walk through the process of creating a clean data model and exposing it through a controller:

  • @RestController: Understanding how this annotation combines @Controller and @ResponseBody to simplify your API development.
  • POJO Design: Best practices for creating simple Java objects that map perfectly to your API responses.
  • Automatic Conversion: See how Spring automatically sets the correct Content-Type to application/json.

Live Practical Session

We build a simple Employee model and a corresponding EmployeeController from scratch. You'll see exactly how to return single objects and lists of objects, and how they appear when requested via a web browser or Postman.

Why Master This?

Mastering how to return objects is the first step in building any real-world backend. It's the foundation for microservices, mobile app backends, and modern web applications. By understanding these Spring Boot fundamentals, you're well on your way to becoming a professional Java developer.

📥 Get the Source Code!

I have shared the full Java source code for this tutorial! Check out the download links in the YouTube video description above to get started with the code.

Friday, 12 February 2021

HTTP Body | Web Services Tutorial

🚀 Want to Master Web Services? 🚀

Subscribe to Ram N Java for easy-to-understand coding tutorials that actually help!

SUBSCRIBE NOW

Understanding the HTTP Body

When you send data across the internet, it doesn't just travel as magic. It's organized into parts. While headers tell the server "who" and "how," the HTTP Body is the actual "what"—it's the real data you are sending or receiving.

What is the HTTP Body?

The HTTP Body (also known as the payload) is the optional section of an HTTP request or response that contains the data. Think of an HTTP message like a physical letter: the headers are the envelope with the address, and the body is the actual letter inside.

When Do We Use a Body?

Not every request needs a body. For example, a GET request usually doesn't have one because you're just asking for data. However, you'll see a body in:

  • POST Requests: When you're submitting a form or creating a new user.
  • PUT/PATCH Requests: When you're updating existing information.
  • Responses: When the server sends back the HTML for a website or JSON data for an app.

Common Data Formats

The data in a body can come in many flavors. The most common ones for developers today are:

  • JSON (JavaScript Object Notation): The standard for modern APIs.
  • HTML: The code that builds the web pages you see.
  • XML: An older, more structured format still used in some systems.
  • Form Data: What browsers send when you click "Submit" on a web form.

Why the 'Content-Type' Header Matters

The body and headers work together. You must use the Content-Type header to tell the receiver how to read the body. If you send JSON but don't tell the server it's JSON, the server might not know how to process your data!

Check Out More Tutorials

Expand your knowledge with these other videos from the Ram N Java channel:

HTTP headers: Content-Type header | Web Services Tutorial

🚀 Ready to Master REST APIs? 🚀

Join the Ram N Java community for the best step-by-step tech tutorials that simplify your coding journey!

SUBSCRIBE NOW

Understanding the Content-Type Header

When two computers talk to each other over the internet, they need to agree on what language they are speaking. The Content-Type Header is the tool we use to make that happen. Without it, a server might receive data but have no idea how to read it.

What is Content-Type?

The Content-Type header tells the receiver (the server or the browser) the media type of the data being sent in the HTTP body. It’s like a label on a box that says "Fragile" or "Books"—it tells the receiver exactly what to expect inside the package.

Common Content Types

In modern web development and REST APIs, you will see these types almost every day:

  • application/json: The most popular choice for APIs. It sends data as a structured JavaScript object.
  • text/html: Used when the server is sending back a full web page to be rendered by your browser.
  • application/xml: An older but very structured format often used in enterprise systems.
  • multipart/form-data: Used when you are uploading files, like images or documents, via a web form.

Why Is It So Important?

If you send a JSON body but forget to set the Content-Type to application/json, the server might try to read it as plain text and fail. This is a very common cause of bugs for beginners! Always double-check your headers to ensure smooth communication between your frontend and backend.

Check Out More From My Channel

Enhance your skills with these other helpful tutorials from Ram N Java:

Thursday, 10 September 2020

MongoDB Introduction | MongoDB Tutorial for Beginners

🚀 Master the Future of Databases!

Want to build lightning-fast applications? Subscribe to Ram N Java for the best beginner-friendly tech tutorials that make complex coding simple!

🔔 JOIN THE COMMUNITY NOW

An Introduction to NoSQL with MongoDB

Are you ready to move beyond traditional tables and rows? In the modern era of high-speed apps and massive data, NoSQL is the backbone of the tech world. MongoDB is the leading choice for developers who need flexibility, speed, and massive scale.

What Exactly is NoSQL?

NoSQL stands for "Not Only SQL." Unlike traditional relational databases (SQL) that require a strict schema of columns and rows, NoSQL databases like MongoDB use a document-oriented approach. This allows you to store data in a way that feels natural to programming, similar to JSON objects.

Key Benefits for Beginners

  • Flexibility: You don't need to define a complex structure before you start saving data.
  • Scalability: MongoDB handles massive amounts of data by spreading it across multiple servers effortlessly.
  • Speed: Optimized for high-performance read and write operations, making your apps feel snappy.

💡 Pro Tip for New Developers

Think of MongoDB documents as folders in a filing cabinet. Each folder can contain different types of information without needing to follow the exact same format as every other folder. This "schema-less" nature is why it's so popular for rapid app development!

Boost Your Skills with More Tutorials:

Thursday, 28 May 2020

Nested Arrays in JSON Object | JSON Tutorial

How to delete an item from the JSON Array? | JSON Tutorial

How to modify the JSON Array? | JSON Tutorial

How to use a for loop to get JSON Array values? | JSON Tutorial

How to use a for-in loop to get JSON Array values? | JSON Tutorial

What is JSON Arrays? | JSON Tutorial

How to delete object properties of Nested JSON Objects? | JSON Tutorial

How to modify the values of Nested JSON Objects? | JSON Tutorial

Online JSON Parser | JSON Tutorial

Nested JSON Objects | JSON Tutorial

JSON - How to loop an Object and get all the Keys and Values? | JSON Tutorial

Tutorials