如何使用GSon公开方法?

时间:2011-09-14 12:25:31

标签: java gson

使用Play Framework,我通过GSON序列化我的模型。我指定哪些字段是暴露的,哪些不是。

这很好但我也想@expose方法。当然,这太简单了。

我该怎么做?

感谢您的帮助!

public class Account extends Model {
    @Expose
    public String username;

    @Expose
    public String email;

    public String password;

    @Expose // Of course, this don't work
    public String getEncodedPassword() {
        // ...
    }
}

5 个答案:

答案 0 :(得分:22)

我遇到此问题的最佳解决方案是制作专用的序列化器:

public class AccountSerializer implements JsonSerializer<Account> {

    @Override
    public JsonElement serialize(Account account, Type type, JsonSerializationContext context) {
        JsonObject root = new JsonObject();
        root.addProperty("id", account.id);
        root.addProperty("email", account.email);
        root.addProperty("encodedPassword", account.getEncodedPassword());

        return root;
    }

}

并在我看来这样使用它:

GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Account.class, new AccountSerializer());
Gson parser = gson.create();
renderJSON(parser.toJson(json));

但让@Expose为一个方法工作会很棒:它会避免只为了显示方法而制作一个序列化器!

答案 1 :(得分:12)

查看Gson on Fire:https://github.com/julman99/gson-fire

这是我创建的一个库,它扩展了Gson来处理暴露方法,结果序列化,后反序列化以及Gson随着时间的推移需要的许多其他事情。

此库在我们的公司Contactive(http://goo.gl/yueXZ3)的生产中用于Android和Java后端

答案 2 :(得分:6)

Gson's @Expose似乎只支持字段。在此注册了一个问题:@Expose should be used with methods

答案 3 :(得分:4)

根据西里尔的回答,结合不同的选择:

带有快捷方式的自定义序列化程序:

public static class Sample
{
    String firstName = "John";
    String lastName = "Doe";

    public String getFullName()
    {
        return firstName + " " + lastName;
    }
}

public static class SampleSerializer implements JsonSerializer<Sample>
{
    public JsonElement serialize(Sample src, Type typeOfSrc, JsonSerializationContext context)
    {
        JsonObject tree = (JsonObject)new Gson().toJsonTree(src);
        tree.addProperty("fullName", src.getFullName());
        return tree;
    }
}

public static void main(String[] args) throws Exception
{
    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(Sample.class, new SampleSerializer());
    Gson parser = gson.create();
    System.out.println(parser.toJson(new Sample()));

}

<强> -OR- 基于注释的序列化程序

public static class Sample
{
    String firstName = "John";
    String lastName = "Doe";

    @ExposeMethod
    public String getFullName()
    {
        return firstName + " " + lastName;
    }
}

public static class MethodSerializer implements JsonSerializer<Object>
{
    public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context)
    {
        Gson gson = new Gson();
        JsonObject tree = (JsonObject)gson.toJsonTree(src);

        try
        {               
            PropertyDescriptor[] properties = Introspector.getBeanInfo(src.getClass()).getPropertyDescriptors();
            for (PropertyDescriptor property : properties)
            {
                if (property.getReadMethod().getAnnotation(ExposeMethod.class) != null)
                {
                    Object result = property.getReadMethod().invoke(src, (Object[])null);
                    tree.add(property.getName(), gson.toJsonTree(result));
                }
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

        return tree;
    }
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) //can use in method only.
public static @interface ExposeMethod {}

public static void main(String[] args) throws Exception
{
    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(Sample.class, new MethodSerializer());
    Gson parser = gson.create();
    System.out.println(parser.toJson(new Sample()));

}

答案 4 :(得分:0)

http://camelcode.org/tutorial/Exclude-fields-from-JSON-using-Gson-with-@Expose.htm

package org.camelcode;

import com.google.gson.annotations.Expose;

public class Book {

    @Expose
    private String author;
    @Expose
    private String title;
    private Integer year;
    private Double price;

    public Book() {
        this("camelcode.org", "Exclude properties with Gson", 1989, 49.55);
    }

    public Book(String author, String title, Integer year, Double price) {
        this.author = author;
        this.title = title;
        this.year = year;
        this.price = price;
    }
}

package org.camelcode;

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

public class WriteGson {

    public static void main(String[] args) {

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

        String json = gson.toJson(new Book());
        System.out.println(json);

        Gson gsonNonExcluded = new Gson();
        String jsonNonExcluded = gsonNonExcluded.toJson(new Book());
        System.out.println(jsonNonExcluded);
    }
}

{"author":"camelcode.org","title":"Exclude properties with Gson"}
{"author":"camelcode.org","title":"Exclude properties with Gson","year":1989,"price":49.55}