Tuesday 29 June 2021

Moshi: json: Customize names while serializing and deserializing

Using Json annotation, you can customize the field names.

 

Example

@Json(name="emp_id")
private Integer id;

Find the below working application.

 

Employee.java

package com.sample.app.model;

import java.util.List;

import com.squareup.moshi.Json;

public class Employee {
	@Json(name="emp_id")
	private Integer id;
	
	@Json(name="emp_name")
	private String name;

	@Json(name="emp_hobbies")
	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.io.IOException;
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[]) throws IOException {
		Employee emp1 = new Employee(1, "Dhatri Sure", Arrays.asList("Trekking", "singing"));

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

		System.out.println("Serializing");
		String json = jsonAdapter.toJson(emp1);
		System.out.println(json);

		Employee emp = jsonAdapter.fromJson(json);

		System.out.println("\nDeserializing");
		System.out.println("id : " + emp.getId());
		System.out.println("name : " + emp.getName());
		System.out.println("hobbies : " + emp.getHobbies());
	}
}


Output

Serializing
{"emp_hobbies":["Trekking","singing"],"emp_id":1,"emp_name":"Dhatri Sure"}

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

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment