2
2
.
.
4
4
.
.
7
7
R
R
e
e
t
t
u
u
r
r
n
n
-
-
D
D
a
a
t
t
a
a
-
-
J
J
S
S
O
O
N
N
I
I
n
n
f
f
o
o
[
[
G
G
]
]
[
[
R
R
]
]
This tutorial shows how to use @ResponseBody to return instance of PersonEntity from the Controller as JSON String.
Application Schema [Results]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables @Controller, @RequestMapping and Tomcat HTTP Server.
PersonEntity
http://localhost:8080/Hello
Tomcat
MyController
{"id":1,"name":"John","age":20}
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: controller_returns_text_json (add Spring Boot Starters from the table)
Create Package: entities (inside main package)
– Create Interface: PersonEntity.java (inside package entities)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside controllers package)
PersonEntity.java
package com.ivoronline.springboot.controller_returns_text_json.entities;
public class PersonEntity {
public Integer id;
public String name;
public Integer age;
}
MyController.java
package com.ivoronline.springboot.controller_returns_text_json.controllers;
import com.ivoronline.springboot.controller_returns_text_json.entities.PersonEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/Hello")
public PersonEntity hello() {
//CREATE INSTANCE
PersonEntity personEntity = new PersonEntity();
personEntity.id = 1;
personEntity.name = "John";
personEntity.age = 20;
//RETURN INSTANCE AS JSON STRING
return personEntity; //{"id":1,"name":"John","age":20}
}
}
R
R
e
e
s
s
u
u
l
l
t
t
s
s
http://localhost:8080/Hello
Application Structure
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>