lundi 6 juillet 2015

Avoid primitive data types default value in json mapping using GSON

public class Test {

    public int num;
    public String name;
    public String email;

    public Test(){

    }

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

By using above class structure i generate json using Gson library,which works perfectly fine ,but the problem is i want to avoid primitive data types default value to json mapping.for example

Test obj=new Test();
obj.setEmail("abc@abc.com");
obj.setName("Mike");
String json= new Gson().toJson(obj);

//output json

{"num":0,"name":"Mike","email":"abc@abc.com"}

In the output json num is assign 0 which is default value for primitive data type int ,i wants to avoid default primitive data type for int in json mapping. I want behavior similar to reference types.if i do not assign value to name or email it will not be generated in output json.

 Test obj=new Test();
 obj.setName("Mike");
 String json= new Gson().toJson(obj);

//output json

 {"num":0,"name":"Mike"}

How to avoid primitive default value in output json?

Any help will be greatly appreciated.





Aucun commentaire:

Enregistrer un commentaire