Tuesday, 29 June 2021

Moshi: Ignore a field from serialization

If you do not exclude a field from serialization, declare that field with ‘transient’ keyword.

 

Example

private transient List<String> hobbies;

 

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 transient 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

{"id":1,"name":"Dhatri Sure"}


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment