[英]Parsing JSON to Enum Fields
in my Android application, I am returned a simple JSON object with simple key value pairs, eg: 在我的Android应用程序中,我返回了带有简单键值对的简单JSON对象,例如:
{"username" : "billySmith", "gender" : 1}
And an enum with the respective field names username
and gender
(String and int, respectively). 还有一个带有相应字段名称
username
和gender
(分别为String和int)的枚举。
I am trying to use Gson to parse the JSON object and populate the enum fields with the json values. 我正在尝试使用Gson解析JSON对象,并用json值填充枚举字段。 I am a little uncertain of how to use GSON with enums.
我不确定如何将GSON与枚举一起使用。 I am familiar with the concept that an instance of an object should be set equal to
gson.fromJson(jsonObect, instanceType.class);
我对一个对象的实例应设置为等于
gson.fromJson(jsonObect, instanceType.class);
的概念很熟悉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. 为了添加更多细节,我使用了枚举,以便可以从我的android项目中的任何地方检索值。
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 其中“结果”是HTTP响应的实体的字符串表示形式
GlobalEnum snippet: GlobalEnum代码段:
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. *编辑:改写:我有一个枚举,并且我有一个jsonObject。 Both the enum and JSON object have "username" and "gender".
枚举和JSON对象都具有“用户名”和“性别”。 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.
使用Gson,我想解析JSON对象,以便将JSONobject中的值分配给Enum中的各个字段。
As I said in the comment you need create a type adapter to be able to get your enum during json parsing. 正如我在评论中所说,您需要创建一个类型适配器,以便能够在json解析期间获取您的枚举。 This is an example of what i have done for my purposes.
这是我为自己的目的所做的一个例子。 In your enum create
TypeAdapterFactory gsonTypeAdaptor
like so: 在您的枚举中,如下创建
TypeAdapterFactory gsonTypeAdaptor
:
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);
一个适配器就位,向您的
gson builder
注册,如下所示: builder.registerTypeAdapterFactory(<your enum>.gsonTypeAdaptor);
Let me know if this was useful. 让我知道这是否有用。
You may have misunderstood the meaning of an Enum
in Java. 您可能误解了Java中的
Enum
的含义。 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
. 我想以下逻辑将为您提供更好的服务,将
JSON
解析为Enums
时免于这种麻烦。
First, a UserInformation
Java Bean class, wrapping the username
and gender
fields: 首先,一个
UserInformation
Java Bean类,包装username
和gender
字段:
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: 然后,将您的
GlobalEnum
类重命名为GlobalValues
并进行修改以用作值容器:
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. 然后是将
JSON
字符串解析为UserInformation
对象,然后将其存储在GlobalValues
类上的逻辑。
String jsonStr = "{\"username\" : \"billySmith\", \"gender\" : 1}";
Gson gson = new Gson();
GlobalValues.userInformation = gson.fromJson(jsonStr, UserInformation.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.