- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下两种类型的 JSON 字符串,它们都有一个“type”字段,但“content”字段具有不同的结构。
{"type": "Login", "content": {"username": "a", "password": "b"}}
{"type": "Forward", "content": {"deviceId": "a", "password": "b"}}
我想将它们解析为 Java 对象。现在我有两个类(class):
class Login {
String username;
String password;
}
class Forward {
String deviceId;
}
现在的问题是,我必须先解析 json 消息的“部分”(即“类型”部分),然后才能决定使用哪个类来继续解析“内容”。
有没有办法进行这种“两步”解析?
我尝试过以下方法:
首先将json消息解析成该类的实例:
class Request {
RequesType type;
String content;
}
然后根据类的解析“type”字段,我可以决定使用哪个类,即使用 res = gson.fromJson(request.content, Forward.class);
或res = gson.fromJson(content, Login.class)
;
但是我传入的 json 是
{"type": "Forward", "content":{"deviceId":"1"}}
我收到的错误是预期的字符串,但实际上是对象,所以我不知道如何继续。任何建议将不胜感激!
最佳答案
也许你想使用 GSON 的 RuntimeTypeAdapterFactory 。它允许您从 type 字段确定要自动反序列化的类的类型:默认情况下方便地命名为 type。
为了让 GSON 拥有反序列化的继承权,我建议对 POJO 进行一些小的更改。创建Request
类,例如:
@Getter @Setter
public class Request {
private String type;
@Getter @Setter
public static class Content {
String password;
}
}
覆盖它和每个请求类型的内容,例如:
@Getter @Setter
public class ForwardRequest extends Request {
@Getter @Setter
public static class ForwardContent extends Content {
private String deviceId;
}
private ForwardContent content;
}
和
@Getter @Setter
public class LoginRequest extends Request {
@Getter @Setter
public static class LoginContent extends Content {
private String username;
}
private LoginContent content;
}
对于上面这样的类,它只是:
@Test
public void test() {
// Tell the top class
RuntimeTypeAdapterFactory<Request> rttaf = RuntimeTypeAdapterFactory.of(Request.class)
// Register inheriting types and the values per type field
.registerSubtype(ForwardRequest.class, "Forward")
.registerSubtype(LoginRequest.class, "Login");
Gson gson = new GsonBuilder().setPrettyPrinting()
.registerTypeAdapterFactory(rttaf)
.create();
// Constructed an array of your two types to be deserialized at the same time
String jsonArr = "["
+ "{\"type\": \"Login\", \"content\": {\"username\": \"a\", \"password\": \"b\"}}"
+ ","
+ "{\"type\": \"Forward\", \"content\": {\"deviceId\": \"a\", \"password\": \"b\"}}"
+ "]";
// Deserialize the array as Request[]
Request[] requests = gson.fromJson(jsonArr, Request[].class);
log.info("{}", requests[0].getClass());
log.info("{}", requests[1].getClass());
}
上述输出类似于:
class org.example.gson.LoginRequest
class org.example.gson.ForwardRequest
您只需复制答案顶部链接中提供的文件即可将 RuntimeTypeAdapterFactory
包含到您的项目中。
更新:关于反序列化 type
或包含类型信息的任何其他字段:GSON 故意将其遗漏。它是一种 transient 场,不是吗?在反序列化之前,您需要知道 type
的值,这样 GSON 就不再费心去反序列化它了。
作为另一个例子 - 为了澄清这一点 - 如果您更改测试字符串,例如:
String jsonArr = "["
+ "{\"type\": \"LoginRequest\", \"content\": {\"username\": \"a\", \"password\": \"b\"}}"
+ ","
+ "{\"type\": \"ForwardRequest\", \"content\": {\"deviceId\": \"a\", \"password\": \"b\"}}"
+ "]";
因此该类型包含类的简单名称(通常是情况)你可以注册子类型,就像:
.registerSubtype(ForwardRequest.class)
.registerSubtype(LoginRequest.class);
并且 GSON 期望类简单名称作为 JSON 类型属性的值。为什么要将类名保存在单独的字段中,因为它是可获取的 Class.getSimpleName()
?
但是,您当然有时可能需要将其序列化到其他客户端。
关于java - Gson:基于另一个字段的动态字段解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54849784/
我试图让 gson 在 java 项目上工作,但每次运行时都会出现上述错误。我没有使用任何闪存 IDE,只是 vim,我看到的与我的问题相关的每个问题都与 eclipse 及其部署设置有关。我希望有人
我一直在关注将对象数组转换为 JSON 的教程,但我遇到了一些找不到解决方案的错误。 代码 第 60 - 64 行 Gson gson = new Gson().toJson(data); respo
我正在创建一个新的 Netty 管道,我正在尝试: 避免过早优化。 编写易于向我的一位实习生解释的代码。 这种工厂方法当然很容易解释: public String toJSON() { Gso
我尝试在程序中使用 Unirest,但不断收到此错误 java.lang.NoSuchMethodError: com.google.gson.Gson.newBuilder()Lcom/google
// Retrofit compile 'com.squareup.retrofit2:retrofit:2.1.0' // JSON Parsing compile 'com.google.code
我正在尝试将 Gson 与接口(interface)一起使用: public interface Photo { public int getWidth(); } public class D
我正在执行一个 Web 服务,这是我的响应,但是当我尝试使用 Gson 库将此 JSONObject(org.json.JSONObject) 转换为特定对象时,我的应用程序崩溃了。所以,我不知道为什
我有以下 .json 文件 - { "IDs":[ "1716136233", "2030187302", "204897807
我试图在我的项目中使用 GSON,但我的应用程序崩溃了,logcat 说找不到 com.google.gson.Gson。我已将 import com.google.gson.Gson 放在我的类文件
在下面的示例中,我尝试序列化我的自定义类Couple,其中包含Point2D 类型的字段。 我发现,SErialzing 的过程取决于 DEserializer 的存在。 此外,如果存在反序列化器,则
我有课 class ThreadComment( banned: Int, closed: Int, comment: String?, date: String?,
使用 gson 解析 json 时,我有一个奇怪的行为。我使用这个代码: private static Container parseContainer(String containerJson) {
我注意到 GSON HTML 转义 字符,可以通过使用disableHtmlEscaping()来禁用它构建器配置方法。但我的问题是 - 为什么 GSON 默认情况下会进行 HTML 转义?不进行 H
我注意到一个奇怪的问题。我可以使用 Junit 运行我的测试用例,但是当我使用 maven 运行时,其中一个测试用例失败。它提示找不到 Gson 类 def。 我能够在 Maven 依赖项中看到 Gs
我有一个看起来像这样的 json {response:{"status":{"....."},data:[{"name":"Alice","id":"123"},{"name":"Jack","id"
所以,我的应用已经发布了将近一年,但没有看到这个问题,现在它出现了。 即使是现在,我的手机上的调试版本也没有这个问题。我对从 Android Studio 打开的任何模拟器没有任何问题。然而,Goog
我是 Android 开发环境的新手,因此需要专家的帮助。 java.lang.NoClassDefFoundError: com.google.gson.Gson 项目中包含 Gson 库,但是当从
总结 我在我的 android 应用程序中使用 Retrofit 和 Gson 有一段时间了,但是我从服务器获得的 ID 是 13 位数字。 Gson 自动将这些数字转换为科学计数法,然后将其转换为
我正在使用一个大的 JSON 对象,它具有来自多个请求的响应。 我正在处理的部分只需要很少的对象,而且它们并不总是在前面。例如 json 结构是: ** json = { mainDocume
我有一个休息网络服务: @Path("/tranreq") public class TranscriptRequesterResource { private static final Gs
我是一名优秀的程序员,十分优秀!