简体   繁体   中英

Parsing JSON to Enum Fields

in my Android application, I am returned a simple JSON object with simple key value pairs, eg:

{"username" : "billySmith", "gender" : 1}

And an enum with the respective field names username and gender (String and int, respectively).

I am trying to use Gson to parse the JSON object and populate the enum fields with the json values. I am a little uncertain of how to use GSON with enums. I am familiar with the concept that an instance of an object should be set equal to gson.fromJson(jsonObect, instanceType.class); .

To add more detail, I am using Enums so that the values can be retrieved from anywhere in my android project.

if (response.getStatusLine().getStatusCode() == 200 && result != "")
{                               
    GlobalEnum globalEnum = GlobalEnum.getInstance();
    Gson gson = new GsonBuilder().create();
    globalEnum = gson.fromJson(result, GlobalEnum.class);
}

where "result" is the string representation of an HTTP Response's entity

GlobalEnum snippet:

public enum GlobalEnum
{
    INSTANCE;

    private String username;
    private int gender;

    public static GlobalEnum getInstance()
    {
        return INSTANCE;
    }

    public int getGender()
    {
        return gender;
    }

    public void setGender(int gender)
    {
        this.gender = gender;
    }
}

*Edit: Reworded: I have an enum, and I have a jsonObject. Both the enum and JSON object have "username" and "gender". using Gson, I would like to parse the JSON object so that the Values from the JSONobject will be assigned to the respective fields in the Enum.

As I said in the comment you need create a type adapter to be able to get your enum during json parsing. This is an example of what i have done for my purposes. In your enum create TypeAdapterFactory gsonTypeAdaptor like so:

public static TypeAdapterFactory gsonTypeAdaptor = new TypeAdapterFactory() {
        @Override
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            Class<T> rawType = (Class<T>) type.getRawType();
            if (!(rawType.isEnum() && Predicates.assignableFrom(rawType).apply(<your enum>.class))) {
                return null;
            }
            return new TypeAdapter<T>() {
                public void write(JsonWriter out, T value) throws IOException {
                    if (value == null) {
                        out.nullValue();
                    } else {
                        out.value(((<your enum>)value).name);
                    }
                }
                public T read(JsonReader reader) throws IOException {
                    if (reader.peek() == JsonToken.NULL) {
                        reader.nextNull();
                        return null;
                    } else {
                        return (T) <get your enum by using reader.nextString()>;
                    }
                }
            };
        }
    };

one adapter is in place, register it with your gson builder like so: builder.registerTypeAdapterFactory(<your enum>.gsonTypeAdaptor);

Let me know if this was useful.

You may have misunderstood the meaning of an Enum in Java. They usually shouldn't be opened to modifications on runtime like this.

I guess the following logic would serve you better, saving you from this kind of trouble when parsing JSON into Enums .

First, a UserInformation Java Bean class, wrapping the username and gender fields:

public class UserInformation
{
    private String username;
    private int gender;

    public UserInformation(String username, int gender)
    {
        this.username = username;
        this.gender = gender;
    }

    public String getUsername()
    {
        return username;
    }
    public void setUsername(String username)
    {
        this.username = username;
    }
    public int getGender()
    {
        return gender;
    }
    public void setGender(int gender)
    {
        this.gender = gender;
    }
}

Then your GlobalEnum class, renamed to GlobalValues and modified to work as a value container:

public abstract class GlobalValues
{
    // You can also create get/set methods for encapsulation if you want
    public static UserInformation userInformation;
}

And then the logic on which you are parsing your JSON String into your UserInformation object, and then storing it on your GlobalValues class.

String jsonStr = "{\"username\" : \"billySmith\", \"gender\" : 1}";

Gson gson = new Gson();

GlobalValues.userInformation = gson.fromJson(jsonStr, UserInformation.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM