Tuesday 29 June 2021

Moshi: Convert json to Java object

Step 1: Get a JsonAdapter instance.

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

 

Step 2: Convert the json string to java object.

Employee emp = jsonAdapter.fromJson(str);

 

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;
	}

}

 

JsonStringToObject.java

package com.sample.app;

import java.io.IOException;

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

public class JsonStringToObject {
	public static void main(String args[]) throws IOException {
		String str = "{\"hobbies\":[\"Trekking\",\"singing\"],\"id\":1,\"name\":\"Dhatri Sure\"}";

		Moshi moshi = new Moshi.Builder().build();
		JsonAdapter<Employee> jsonAdapter = moshi.adapter(Employee.class);
		
		Employee emp = jsonAdapter.fromJson(str);
		
		System.out.println("id : " + emp.getId());
		System.out.println("name : " + emp.getName());
		System.out.println("hobbies : " + emp.getHobbies());
	}

}

Output

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

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment