Genson - How to convert Java object to JSON and JSON to Java object
In this section, we will show you how to convert Java object to JSON and JSON to Java object with Genson.
Note
Genson is a complete json <-> java conversion library, providing full databinding, streaming and much more.
Gensons main strengths?
- Easy to use and just works!
- Its modular and configurable architecture.
- Speed and controlled small memory foot print making it scale.
Note
Genson is a complete json <-> java conversion library, providing full databinding, streaming and much more.
Gensons main strengths?
- Easy to use and just works!
- Its modular and configurable architecture.
- Speed and controlled small memory foot print making it scale.
Note
JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.
JSON is built on two structures:
- A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
- An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Note
JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.
JSON is built on two structures:
- A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
- An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
1. Download Genson
<dependency>
<groupId>com.owlike</groupId>
<artifactId>genson</artifactId>
<version>1.6</version>
</dependency>
2. JSON to Java Objects
A User POJO, later uses this for conversion.
User.java
public class User {
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
In Genson, we can use Genson.deserialize() to convert JSON to Java Objects.
Main.java
import com.owlike.genson.Genson;
public class Main {
public static void main(String[] args) {
String json = "{\"name\":\"sibin\", " +
"\"email\":\"sibin@gmail.in\"},";
User user = new Genson().deserialize(json,User.class );
System.out.println(user);
}
}
Console Output:
User{name='sibin', email='sibin@gmail.in'}
3. Java Objects to JSON
In Genson, we can use Genson.serialize()
to convert Java Objects to JSON.
Main.java
import com.owlike.genson.Genson;
public class Main {
public static void main(String[] args) {
User user = new User();
user.setName("sibin");
user.setEmail("sibin@gmail.in");
String json= new Genson().serialize(user);
System.out.println(json);
}
}
Console Output:
{"email":"sibin@gmail.in","name":"sibin"}
More related topics,