Return JSON in a Micronaut Controller

In this tutorial, we will learn how to return JSON in a Micronaut controller using simple and practical examples. Table of contents 1. Setting Up the Micronaut Project 2. Returning a JSON Object Define a Data Model What is @Serdeable? Create a Controller Run the Application 3. Returning a List of JSON Objects Run the …

Read more

Spring @ResponseBody Annotation

In the Spring framework, the @ResponseBody annotation tells the Spring framework to write the method’s return type to the HTTP response body (not placed in a Model or interpreted as a view name). Spring 3.0 introduced the @ResponseBody annotation on the method level. Spring 4.0 enhanced the @ResponseBody annotation to put on the class level, …

Read more

JAX-RS – How to read response body from a post request?

In JAX-RS, we can use response.readEntity(String.class) to read the response body from a post request. import jakarta.ws.rs.core.Response; Response response = //… // read response body String body = response.readEntity(String.class); P.S Tested with Jersey 3.x 1. Problem Below is a JAX-RS POST request endpoint to accept a JSON input and return a JSON response. // POST, …

Read more

Jersey and JSON examples (EclipseLink MOXy)

This article shows how to return a JSON response in the Jersey application, using EclipseLink MOXy. Tested with Jersey 3.0.2 EclipseLink MOXy 3 Jetty 11, HTTP Server Java 11 Maven 3 SLF4J, Logback, redirect Jersey J.U.L logs to logback JUnit 5 and JSONassert 1.5 (Unit Test) org.json 20210307, JSONObject Table of contents 1. EclipseLink MOXy …

Read more

Jersey and Jetty HTTP Server examples

This article shows how to start a Jetty HTTP Sever to run a JAX-RS or Eclipse Jersey application. Tested with Jersey 3.0.2 Jetty 11 Jackson 2.12.2 JUnit 5.4.0 (unit test) JSONassert 1.5.0 (unit test) Maven 3.8.3 Java 11 Tables of contents 1. Using Jersey with Jetty HTTP Server 2. Project Directory 3. Project dependencies 4. …

Read more

Java 11 HttpClient Examples

This article shows you how to use the new Java 11 HttpClient APIs to send HTTP GET/POST requests, and some frequent used examples. HttpClient httpClient = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .followRedirects(HttpClient.Redirect.NORMAL) .connectTimeout(Duration.ofSeconds(20)) .proxy(ProxySelector.of(new InetSocketAddress("proxy.yourcompany.com", 80))) .authenticator(Authenticator.getDefault()) .build(); 1. Synchronous Example This example sends a GET request to https://httpbin.org/get, and print out the response header, status code, and …

Read more

OkHttp – How to send HTTP requests

This article shows you how to use the OkHttp library to send an HTTP GET/POST requests and some frequent used examples. P.S Tested with OkHttp 4.2.2 pom.xml <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.2.2</version> </dependency> 1. Synchronous Get Request OkHttpExample1.java package com.mkyong.http; import okhttp3.Headers; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import java.io.IOException; public class OkHttpExample1 { // only …

Read more

FastJson – Convert Java objects to / from JSON

FastJson provides easily APIs to convert Java objects to / from JSON JSON.toJSONString – Java objects to JSON JSON.parseObject – JSON to Java objects JSON.parseArray – JSON array to List of Java objects Note You may have interest to read this How to parse JSON with Jackson Overall, the FastJson is really simple and easy …

Read more

JSON.simple – How to parse JSON

In this tutorial, we will show you how to parse JSON with JSON.simple Note You may have interest to read – How to parse JSON with Jackson or Gson JSON.simple short history This project was formerly JSON.simple 1.x from a Google code project by Yidong, now maintaining by Clifton Labs, read this JSON.simple history P.S …

Read more

How to parse JSON string with Jackson

This article uses the Jackson framework to parse JSON strings in Java. Table of contents: 1. Download Jackson 2. Parse JSON String with Jackson 3. Parse JSON Array with Jackson 4. Convert Java Object to JSON String 5. Convert JSON String to Java Object 6. Download Source Code 7. References P.S Tested with Jackson 2.17.0 …

Read more

Spring Test – How to test a JSON Array in jsonPath

In Spring, we can use Hamcrest APIs like hasItem and hasSize to test a JSON Array. Review the following example : package com.mkyong; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import …

Read more

Spring REST Error Handling Example

In this article, we will show you error handling in Spring Boot REST application. Technologies used : Spring Boot 2.1.2.RELEASE Spring 5.1.4.RELEASE Maven 3 Java 8 1. /error 1.1 By default, Spring Boot provides a BasicErrorController controller for /error mapping that handles all errors, and getErrorAttributes to produce a JSON response with details of the …

Read more

JSONAssert – How to unit test JSON data

In Java, we can use JSONAssert to unit test JSON data easily. 1. Maven pom.xml <dependency> <groupId>org.skyscreamer</groupId> <artifactId>jsonassert</artifactId> <version>1.5.0</version> </dependency> 2. JSON Object To test the JSON Object, Strict or not, fields order does not matter. If the extended fields are matter, enable the strict mode. 2.1 When the strictMode is off. JSONObject actual = …

Read more

cURL post JSON data on Windows

On Windows, the key to send JSON data is double-quotes like this -d "{\"name\":\"Spring Forever\"}" cURL to POST a JSON data curl -X POST localhost:8080/books -H "Content-type:application/json" -d "{\"name\":\"Spring Forever\",\"author\":\"pivotal\"}" References cURL – Post JSON data to Spring REST

cURL – PUT request examples

Example to use cURL -X PUT to send a PUT (update) request to update the user’s name and email. Terminal $ curl -X PUT -d ‘name=mkyong&[email protected]’ http://localhost:8080/user/100 If the REST API only accepts json formatted data, try this Terminal $ curl -X PUT -H "Content-Type: application/json" -d ‘{"name":"mkyong","email":"[email protected]"}’ http://localhost:8080/user/100 References cURL official website cURL – …

Read more

Spring Boot Ajax example

This article will show you how to use jQuery.ajax to send a HTML form request to a Spring REST API and return a JSON response. Tools used : Spring Boot 1.5.1.RELEASE Spring 4.3.6.RELEASE Maven 3 jQuery Bootstrap 3 Note You may interest at this classic Spring MVC Ajax example 1. Project Structure A standard Maven …

Read more

cURL – POST request examples

Some cURL POST request examples for self reference. 1. Normal POST 1.1 To POST without data. $ curl -X POST http://localhost:8080/api/login/ 1.2 To POST with data. $ curl -d "username=mkyong&password=abc" http://localhost:8080/api/login/ 1.3 Spring REST to accept normal POST data. @PostMapping("/api/login") public ResponseEntity<?> login(@RequestParam("username") String username, @RequestParam("password") String password) { //… } @PostMapping("/api/login") public ResponseEntity<?> login(@ModelAttribute …

Read more

cURL – Post JSON data to Spring REST

This article shows you how to use cURL command to POST JSON data to a Spring REST API. 1. Spring REST A Simple Spring REST API to validate a login. LoginController.java package com.mkyong.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller public class LoginController { private final Logger …

Read more

jQuery – Ajax request return 200 OK but error event is fired?

Review a jQuery Ajax form submit. $(document).ready(function () { $("#hostingForm").submit(function (e) { e.preventDefault(e); var data = {} data["id"] = $("#id").val(); data["domain"] = $("#domain").val(); data["name"] = $("#name").val(); //… $.ajax({ type: "POST", contentType: "application/json", url: "{{home}}/hosting/update", data: JSON.stringify(data), dataType: ‘json’, timeout: 600000, success: function (data) { console.log("SUCCESS: ", data); }, error: function (e) { console.log("ERROR: ", e); …

Read more

Jackson 2 – Convert Java Object to / from JSON

In this tutorial, we will show you how to use Jackson 2.x to convert Java objects to / from a JSON. 1. Basic 1.1 Convert a Staff object to from JSON. writeValue(…) – Java Objects to JSON ObjectMapper mapper = new ObjectMapper(); // Java object to JSON file mapper.writeValue(new File("c:\\test\\staff.json"), new Staff()); // Java object …

Read more

jQuery loop over JSON string – $.each example

Review a simple jQuery example to loop over a JavaScript array object. var json = [ {"id":"1","tagName":"apple"}, {"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"}, {"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"} ]; $.each(json, function(idx, obj) { alert(obj.tagName); }); Above code snippet is working fine, prompts the “apple”, “orange” … as expected. Problem : JSON string Review below example, declares a JSON string (enclosed with single …

Read more

How to access JSON object in JavaScript

Below is a JSON string. JSON String { "name": "mkyong", "age": 30, "address": { "streetAddress": "88 8nd Street", "city": "New York" }, "phoneNumber": [ { "type": "home", "number": "111 111-1111" }, { "type": "fax", "number": "222 222-2222" } ] } To access the JSON object in JavaScript, parse it with JSON.parse(), and access it via …

Read more

Jackson : was expecting double-quote to start field name

A simple example to use Jackson to convert a JSON string to a Map. String json = "{name:\"mkyong\"}"; Map<String,String> map = new HashMap<String,String>(); ObjectMapper mapper = new ObjectMapper(); map = mapper.readValue(json, new TypeReference<HashMap<String,String>>(){}); Problem When the program is executed, it hits following error message org.codehaus.jackson.JsonParseException: Unexpected character (‘n’ (code 110)): was expecting double-quote to start …

Read more

Spring 3 MVC and JSON example

In this tutorial, we show you how to output JSON data in Spring MVC framework. Technologies used : Spring 3.2.2.RELEASE Jackson 1.9.10 JDK 1.6 Eclipse 3.6 Maven 3 P.S In Spring 3, to output JSON data, just puts Jackson library in the project classpath. 1. Project Dependencies Get Jackson and Spring dependencies. pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" …

Read more

Jersey and JSON examples (Jackson)

This article shows how to return a JSON response in the Jersey application, using Jackson 2.x. Tested with Jersey 3.0.2 Grizzly 3 HTTP Server Jackson 2.12.2 Java 11 Maven JUnit 5 and JSONassert 1.5 (Unit Test) Table of contents 1. Jackson as the JSON provider in Jersey 2. Project Directory 3. Project dependencies 4. Jersey …

Read more

Java MongoDB : Convert JSON data to DBObject

MongoDB comes with “com.mongodb.util.JSON” class to convert JSON data directly to a DBObject. For example, data represent in JSON format : { ‘name’ : ‘mkyong’, ‘age’ : 30 } To convert it to DBObject, you can code like this : DBObject dbObject = (DBObject) JSON.parse("{‘name’:’mkyong’, ‘age’:30}"); Example See a full example to convert above JSON …

Read more

How to get Delicious bookmark count with jQuery and JSON

Delicious, the best bookmark website, provides many APIs to let developers to deal with the bookmarks’ data. Here’s an example to use jQuery to retrieve the total number bookmark count of a given URL. Delicious API To get a total number of bookmark, use this http://feeds.delicious.com/v2/json/urlinfo/data?url=xxx.com&callback=? jQuery Ajax jQuery, comes with an easy but powerful …

Read more