如何制作反序列化 json 字符串的 fieldName 到 fieldValue 映射
我有一个类,只有简单的字符串类型字段和一个映射:
class MyClass {
@SerializedName("handle");
String nickName;
Map randomDetails;
}
我的要求是创建 fieldName 到 fieldValue (映射)的映射,但 fieldNames 应该与 @SerializedName 相同,而不是 Myclass 的字段名称。我意识到,对于像 MyClass 这样的复杂类型,我可能必须自己进行一些低级反序列化。有人遇到过这个吗?
I have a class having trivial string typed fields and one map only:
class MyClass {
@SerializedName("handle");
String nickName;
Map randomDetails;
}
My requirement is to create a map of fieldName to fieldValue (Map) but the fieldNames should be the same as @SerializedName rather than Myclass's field name. I realize that for a complex type like MyClass I may have to do some low-level deserialization myself. Has anyone come across this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用库,则不需要执行任何低级工作。
我还没有使用过它,但是 Jackson 看起来它可以满足您的需要。
如果您不需要使用
@SerializedName
注释,那就特别容易,因为 Jackson 提供了一套 它自己的注释完全可以满足您的需要 - (请参阅@JsonProperty
注释)。如果您使用 杰克逊树模型 操作模式,您应该得到类似基于地图的结果正在寻找。
If you use a library, you shouldn't need to do any low-level work.
I haven't used it (yet) but Jackson looks like it'll do what you need.
It would be especially easy if you're not required to use that
@SerializedName
annotation, as Jackson provides a suite of its own annotations which do exactly what you need - (see the@JsonProperty
annotation).If you use the Jackson Tree Model mode of operation, you should get something like the map-based results you're looking for.
(我想我明白这个问题涉及如何使用 Gson 将 JSON 映射结构反序列化为 Java
Map
。)Gson 目前需要更多有关
Map
的类型信息> 比原始问题中提供的 Java 类结构。不要声明randomDetails
是一个普通的旧Map
,而是让 Gson 知道它是一个Map
。然后,以下示例 JSON 和简单的反序列化代码将按预期运行。input.json 内容:
Foo.java:
请注意,这会将
Map
中的所有值转换为Strings
。如果您想要更通用的东西,例如Map
,或者randomDetails
必须是普通的旧Map
,没有其他类型信息,那么有必要实现自定义反序列化处理,如中所述用户指南。 (不幸的是,如果声明的 Java 类型只是Object
,Gson 当前不会自动从 JSON 基元自动生成String
或基元类型的 Java 值。因此有必要来实现自定义反序列化。)这是一个这样的示例。
(I think I understand that the question concerns how to use Gson to deserialize a JSON map structure to a Java
Map
.)Gson currently needs a little bit more type information about the
Map
than the Java class structure in the original question provides. Instead of declaring thatrandomDetails
is a plain oldMap
, let Gson know that it's aMap<String, String>
. Then, the following example JSON and simple deserialization code runs as expected.input.json Contents:
Foo.java:
Note that this converts all values in the
Map
intoStrings
. If you wanted something more generic, like aMap<String, Object>
, or ifrandomDetails
must be a plain oldMap
without additional type information, then it's necessary to implement custom deserialization processing, as described in the user guide. (This is a situation where Gson unfortunately does not currently automatically generate Java values ofString
or primitive type from JSON primitives, if the declared Java type is simplyObject
. Thus it's necessary to implement the custom deserialization.)Here's one such example.