gpt4 book ai didi

json - Gson 可选和必填字段

转载 作者:IT老高 更新时间:2023-10-28 12:44:49 30 4
gpt4 key购买 nike

应该如何处理Gson以及必填字段和可选字段?

由于所有字段都是可选的,因此我不能根据响应 json 是否包含某些键而使我的网络请求失败,Gson将简单地将其解析为 null。

我使用的方法 gson.fromJson(json, mClassOfT);

例如,如果我有以下 json:

{"user_id":128591, "user_name":"TestUser"}

还有我的类(class):

public class User {

@SerializedName("user_id")
private String mId;

@SerializedName("user_name")
private String mName;

public String getId() {
return mId;
}

public void setId(String id) {
mId = id;
}

public String getName() {
return mName;
}

public void setName(String name) {
mName = name;
}
}

如果 json 不包含 user_iduser_name 键,是否有任何选项可以让 Gson 失败?

在很多情况下,您可能至少需要解析一些值,而另一种可能是可选的?

是否有任何模式或库可用于全局处理这种情况?

谢谢。

最佳答案

正如您所注意到的,Gson 无法定义“必填字段”,如果 JSON 中缺少某些内容,您只会在反序列化对象中获得 null

这是一个可重复使用的反序列化器和注释,可以做到这一点。限制是,如果 POJO 需要按原样自定义反序列化器,您必须更进一步,在构造函数中传入 Gson 对象以反序列化到对象本身或移动注释 checkout 一个单独的方法并在您的反序列化器中使用它。您还可以通过创建自己的异常并将其传递给 JsonParseException 来改进异常处理,以便可以通过调用者中的 getCause() 检测到它。

总而言之,在绝大多数情况下,这将起作用:

public class App
{

public static void main(String[] args)
{
Gson gson =
new GsonBuilder()
.registerTypeAdapter(TestAnnotationBean.class, new AnnotatedDeserializer<TestAnnotationBean>())
.create();

String json = "{\"foo\":\"This is foo\",\"bar\":\"this is bar\"}";
TestAnnotationBean tab = gson.fromJson(json, TestAnnotationBean.class);
System.out.println(tab.foo);
System.out.println(tab.bar);

json = "{\"foo\":\"This is foo\"}";
tab = gson.fromJson(json, TestAnnotationBean.class);
System.out.println(tab.foo);
System.out.println(tab.bar);

json = "{\"bar\":\"This is bar\"}";
tab = gson.fromJson(json, TestAnnotationBean.class);
System.out.println(tab.foo);
System.out.println(tab.bar);
}
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface JsonRequired
{
}

class TestAnnotationBean
{
@JsonRequired public String foo;
public String bar;
}

class AnnotatedDeserializer<T> implements JsonDeserializer<T>
{

public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException
{
T pojo = new Gson().fromJson(je, type);

Field[] fields = pojo.getClass().getDeclaredFields();
for (Field f : fields)
{
if (f.getAnnotation(JsonRequired.class) != null)
{
try
{
f.setAccessible(true);
if (f.get(pojo) == null)
{
throw new JsonParseException("Missing field in JSON: " + f.getName());
}
}
catch (IllegalArgumentException ex)
{
Logger.getLogger(AnnotatedDeserializer.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
Logger.getLogger(AnnotatedDeserializer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
return pojo;

}
}

输出:

This is foothis is barThis is foonullException in thread "main" com.google.gson.JsonParseException: Missing field in JSON: foo

关于json - Gson 可选和必填字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21626690/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com