0

I am trying to serialize and deserialize an enum which is inside an interface via GSON. please help if someone has something on it. Thanks in advance.. :)

Here is my interface ..

public interface Module {
    @Expose
    public enum CATEGORY {
        INPUT,
        OUTPUT,
        LIGHTS,        
        COMMUNICATION,
        ...
    }
    @Expose
    public enum TYPE {
        INPUT,
        OUTPUT,
        ANALOG,
        DIGITAL,
        ...
    }
}
aditya
  • 3
  • 3

2 Answers2

0

Try this:

Module.CATEGORY m = Module.CATEGORY.COMMUNICATION;
Gson gson = new Gson();
System.out.println(gson.toJson(m));

this will print the name of your enumerator,

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • one addition for this, i want to use it with Expose notation in here. for example :- @Expose public enum CATEGORY { INPUT, OUTPUT, LIGHTS, COMMUNICATION } – aditya Nov 08 '15 at 07:43
  • Some what like this when we add Expose annotation but it gives error. – aditya Nov 08 '15 at 07:51
0

Try code at the below.

public class Tester {

    public static void main(String[] args) {

        Module.CATEGORY comm = Module.CATEGORY.LIGHTS;
        Gson gson = new Gson();

        String json = gson.toJson(comm);
        if (gson.fromJson(json, Module.CATEGORY.class) == Module.CATEGORY.LIGHTS)
            System.out.println("It works!");

    }
}

prints:

It works!

Serialize your enum via.

public interface Module {

    public enum CATEGORY implements Serializable {
        INPUT,
        OUTPUT,
        LIGHTS,        
        COMMUNICATION
    }
    public enum TYPE implements Serializable {
        INPUT,
        OUTPUT,
        ANALOG,
        DIGITAL
    }
}
Sedat Polat
  • 1,631
  • 2
  • 18
  • 28
  • one addition for this, i want to use it with Expose annotation in here. Some what like this when we add Expose annotation but it gives error for example :- @Expose public enum CATEGORY { INPUT, OUTPUT, LIGHTS, COMMUNICATION } – aditya Nov 08 '15 at 07:51
  • You should update your question and see the answer for @Expose -> http://stackoverflow.com/a/7430002/668572 – Sedat Polat Nov 09 '15 at 15:00