Convert JSON to Java object
JSON : JavaScript Object Notation
JSON is a lightweight data interchange format.It is not dependent on any programming language.In JSON data is represented in the form of name and value pairs.It is easy to parse and generate the JSON.
For example:
{
"studentId":1,
"studentName":"Akash",
"studentAge":17,
"subjects":[
"science",
"english",
"hindi"
]
}
Convert JSON data to Java object using - Jackson 2
jars required:
- jackson-annotations-2.1.2
- jackson-core-2.6.3
- jackson-databind-2.2.3
Student.java
package com.javainstance;
import java.util.List;
/**
* @author javainstance
*
*/
public class Student {
private int studentId;
private String studentName;
private int studentAge;
private List<String> subjects;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentAge() {
return studentAge;
}
public void setStudentAge(int studentAge) {
this.studentAge = studentAge;
}
public List<String> getSubjects() {
return subjects;
}
public void setSubjects(List<String> subjects) {
this.subjects = subjects;
}
@Override
public String toString() {
return "Student [studentId=" + studentId + ", studentName=" + studentName + ", studentAge=" + studentAge
+ ", subjects=" + subjects + "]";
}
}
student.json
{
"studentId":1,
"studentName":"Akash",
"studentAge":17,
"subjects":[
"science",
"english",
"hindi"
]
}
JsonToObject.java
package com.javainstance;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author javainstance
*
*/
public class JsonToObject {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File("D://Workspace1//JSON//src//student.json");
Student student = null;
try {
student = objectMapper.readValue(file, Student.class);
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(student);
}
}
Output:
Student [studentId=1, studentName=Akash, studentAge=17, subjects=[science, english, hindi]]
References:
Give you suggestion in comments.If you like the post Share with your friends on social network.
You may be interested in: Convert Java Object to JSON.
Convert JSON to Java object
Reviewed by JavaInstance
on
11:44:00 PM
Rating:
Reviewed by JavaInstance
on
11:44:00 PM
Rating:

No matter if some one searches for his essential thing, therefore he/she wishes to be available that in detail, thus that thing is maintained over here. tdameritrade.com login
ReplyDelete
ReplyDeleteHey very interesting blog! yahoo email login