Moshi - 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 Moshi.
Note
Moshi is a modern JSON library for Java that will give us powerful JSON serialization and deserialization in our code with little effort.
Note
Moshi is a modern JSON library for Java that will give us powerful JSON serialization and deserialization in our code with little effort.
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 Moshi
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi</artifactId>
<version>1.13.0</version>
</dependency>
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi-adapters</artifactId>
<version>1.13.0</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 + '\'' +
'}';
}
}
Main.java
public class Main {
public static void main(String[] args) throws IOException {
String json = "{\"name\":\"sibin\", " +
"\"email\":\"sibin@gmail.in\"}";
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<User> jsonAdapter = moshi.adapter(User.class);
User user = jsonAdapter.fromJson(json);
System.out.println(user);
}
}
Console Output:
User{name='sibin', email='sibin@gmail.in'}
3. Java Objects to JSON
Main.java
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
User user = new User();
user.setName("sibin");
user.setEmail("sibin@gmail.in");
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<User> jsonAdapter = moshi.adapter(User.class);
String json = jsonAdapter.toJson(user);
System.out.println(json);
}
}
Console Output:
{"email":"sibin@gmail.in","name":"sibin"}
More related topics,