Moshi is a modern JSON library for Android developed by Square. It is a compact and efficient library that makes it easy to work with JSON in Android applications.
Moshi provides a set of classes for data binding, which allow you to convert JSON to and from Java objects. It also provides classes for streaming JSON, for example for parsing large amounts of data or for generating JSON data on the fly.
Moshi has a number of advanced features, including support for custom serialization and deserialization with custom converters, support for JSON encoding and decoding with custom adapters, and the ability to customize the parsing and generation process. It is widely used in Android applications for working with JSON data.
<!-- https://mvnrepository.com/artifact/com.squareup.moshi/moshi -->
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi</artifactId>
<version>1.14.0</version>
<scope>runtime</scope>
</dependency>
Here is an example of how to use Moshi to parse a JSON string and convert it into a Java object:
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
public class MoshiExample {
public static void main(String[] args) throws IOException {
String json = "[{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}, {\"name\":\"Jane\",\"age\":25,\"city\":\"Chicago\"}]";
Moshi moshi = new Moshi.Builder().build();
Type type = Types.newParameterizedType(List.class, Person.class);
JsonAdapter<List<Person>> adapter = moshi.adapter(type);
List<Person> people = adapter.fromJson(json);
for (Person person : people) {
System.out.println(person.name);
System.out.println(person.age);
System.out.println(person.city);
}
}
}
class Person {
String name;
int age;
String city;
}
To generate a JSON string from a Java object, you can use the toJson
method of the JsonAdapter
class:
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
public class MoshiExample {
public static void main(String[] args) throws IOException {
Person person = new Person("John", 30, "New York");
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<Person> adapter = moshi.adapter(Person.class);
String json = adapter.toJson(person);
System.out.println(json); // Outputs "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"
}
}
class Person {
String name;
int age;
String city;
public Person(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
}