In this post you will learn how to get a Java object from a given JSON.
Step1: Add maven dependency.
Step2: Create a pojo model class
Step3: Create Java Object from Json
Sumit Kumar
Step1: Add maven dependency.
<
dependency
>
<
groupId
>org.codehaus.jackson</
groupId
>
<
artifactId
>jackson-mapper-asl</
artifactId
>
<
version
>1.9.13</
version
>
Step2: Create a pojo model class
public
class
Employee
{
private
Integer id;
private
String firstName;
public
Employee(){
}
public
Employee(Integer id, String name
){
this
.id = id;
this
.name
= name
;
}
public
Integer getId()
{
return
id;
}
public
void
setId(Integer id)
{
this
.id = id;
}
public
String getFirstName()
{
return
name;
}
public
void
setFirstName(String name
)
{
this
.name
= name
;
}
@Override
public
String toString()
{
return
"Employee [id="
+ id +
", name
="
+
name
"]"
;
}
}
Step3: Create Java Object from Json
package
com.sumit.jackson;
import
java.io.File;
import
java.io.IOException;
import
org.codehaus.jackson.JsonGenerationException;
import
org.codehaus.jackson.map.JsonMappingException;
import
org.codehaus.jackson.map.ObjectMapper;
public
class
JSONToJavaExample
{
public
static
void
main(String[] args)
{
Employee employee =
null
;
ObjectMapper mapper =
new
ObjectMapper();
try
{
employee = mapper.readValue(
new
File(
"/home/sumit/employee.json"
),
Employee.
class
);
}
catch
(JsonGenerationException e)
{
e.printStackTrace();
}
catch
(JsonMappingException e)
{
e.printStackTrace();
}
catch
(IOException e)
{
e.printStackTrace();
}
System.out.println(employee);
}
}
Output: Employee [id=
1
, name
=Sumit Kumar]
Note: File
/home/sumit/employee.json Contains following data
{
"id"
:
1
,
"name"
:
"sumit kumar"
}
Thanks
Sumit Kumar