Part 4 – Excluding Fields

[embedyt] https://www.youtube.com/watch?v=qY6R8IadCqA[/embedyt]
Links & DependenciesEmployee.javaMainActivity.java

Library on GitHub with installation instructions:

github.com/google/gson

package com.codinginflow.gsonexample;


import com.google.gson.annotations.Expose;

public class Employee {
    @Expose
    private String firstName;
    @Expose(serialize = false)
    private int age;
    @Expose(deserialize = false)
    private String mail;

    private String password;

    public Employee(String firstName, int age, String mail, String password) {
        this.firstName = firstName;
        this.age = age;
        this.mail = mail;
        this.password = password;
    }
}
package com.codinginflow.gsonexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

        Employee employee = new Employee(
                "John",
                30,
                "john@mail.com",
                "fdfarg2"
        );

        String jsonResult = gson.toJson(employee);

        String json = "{\"age\":30,\"firstName\":\"John\",\"mail\":\"john@mail.com\",\"password\":\"fdfarg2\"}";

        Employee employee1 = gson.fromJson(json, Employee.class);
    }
}