Tuesday 29 June 2021

Moshi: Convert java object to json string

Step 1: Get a JsonAdapter instance.

Moshi moshi = new Moshi.Builder().build();
JsonAdapter<Employee> jsonAdapter = moshi.adapter(Employee.class);

 

Step 2: Convert the object to json.

String json = jsonAdapter.toJson(emp1);

 

Find the below working application.

 

Employee.java

package com.sample.app.model;

import java.util.List;

public class Employee {
	private Integer id;
	private String name;
	private List<String> hobbies;

	public Employee(Integer id, String name, List<String> hobbies) {
		this.id = id;
		this.name = name;
		this.hobbies = hobbies;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<String> getHobbies() {
		return hobbies;
	}

	public void setHobbies(List<String> hobbies) {
		this.hobbies = hobbies;
	}

}

 

ObjectToJsonString.java

package com.sample.app;

import java.util.Arrays;

import com.sample.app.model.Employee;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

public class ObjectToJsonString {
	public static void main(String args[]) {
		Employee emp1 = new Employee(1, "Dhatri Sure", Arrays.asList("Trekking", "singing"));

		Moshi moshi = new Moshi.Builder().build();
		JsonAdapter<Employee> jsonAdapter = moshi.adapter(Employee.class);

		String json = jsonAdapter.toJson(emp1);

		System.out.println(json);
	}
}

Output

{"hobbies":["Trekking","singing"],"id":1,"name":"Dhatri Sure"}

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment