- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我的问题示例:
我们有一个 Apple 的对象类型。苹果有一些成员变量:
String appleName; // The apples name
String appleBrand; // The apples brand
List<Seed> seeds; // A list of seeds the apple has
种子对象如下所示。
String seedName; // The seeds name
long seedSize; // The size of the seed
现在当我得到一个苹果对象时,一个苹果可能有多个种子,或者它可能有一个种子,或者可能没有种子!
带有一个种子的 JSON 苹果示例:
{
"apple" : {
"apple_name" : "Jimmy",
"apple_brand" : "Awesome Brand" ,
"seeds" : {"seed_name":"Loopy" , "seed_size":"14" }
}
}
带有两个种子的 JSON 苹果示例:
{
"apple" : {
"apple_name" : "Jimmy" ,
"apple_brand" : "Awesome Brand" ,
"seeds" : [
{
"seed_name" : "Loopy",
"seed_size" : "14"
},
{
"seed_name" : "Quake",
"seed_size" : "26"
}
]}
}
现在这里的问题是第一个示例是用于种子的 JSONObject,第二个示例是用于种子的 JSONArray。现在我知道它的 JSON 不一致,修复它的最简单方法是修复 JSON 本身,但不幸的是我从其他人那里得到了 JSON,所以我无法修复它。解决此问题的最简单方法是什么?
最佳答案
您需要为 Apple
类型注册一个自定义类型适配器。在类型适配器中,您将添加逻辑以确定是否给您一个数组或单个对象。使用该信息,您可以创建 Apple
对象。
除了以下代码,修改您的 Apple 模型对象,以便不会自动解析 seeds
字段。将变量声明更改为:
private List<Seed> seeds_funkyName;
代码如下:
GsonBuilder b = new GsonBuilder();
b.registerTypeAdapter(Apple.class, new JsonDeserializer<Apple>() {
@Override
public Apple deserialize(JsonElement arg0, Type arg1,
JsonDeserializationContext arg2) throws JsonParseException {
JsonObject appleObj = arg0.getAsJsonObject();
Gson g = new Gson();
// Construct an apple (this shouldn't try to parse the seeds stuff
Apple a = g.fromJson(arg0, Apple.class);
List<Seed> seeds = null;
// Check to see if we were given a list or a single seed
if (appleObj.get("seeds").isJsonArray()) {
// if it's a list, just parse that from the JSON
seeds = g.fromJson(appleObj.get("seeds"),
new TypeToken<List<Seed>>() {
}.getType());
} else {
// otherwise, parse the single seed,
// and add it to the list
Seed single = g.fromJson(appleObj.get("seeds"), Seed.class);
seeds = new ArrayList<Seed>();
seeds.add(single);
}
// set the correct seed list
a.setSeeds(seeds);
return a;
}
});
有关更多信息,请参阅 Gson guide .
关于java - 对象中一个变量的 Gson 自定义解串器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6014674/
我正在尝试创建一个程序,其中字符串的前三个字符重复给定次数,如下所示: foo('Chocolate', 3) # => 'ChoChoCho' foo('Abc', 3) # => 'AbcAbcA
我有以下字符串: std::string str = "Mode:AAA:val:101:id:A1"; 我想分离一个位于 "val:" 和 ":id" 之间的子字符串,这是我的方法: std::st
DNA 字符串可以是任意长度,包含 5 个字母(A、T、G、C、N)的任意组合。 压缩包含 5 个字母(A、T、G、C、N)的 DNA 字母串的有效方法是什么?不是考虑每个字母表 3 位,我们可以使用
是否有一种使用 levenstein 距离将一个特定字符串与第二个较长字符串中的任何区域进行匹配的好方法? 例子: str1='aaaaa' str2='bbbbbbaabaabbbb' if str
使用 OAuth 并使用以下函数使用我们称为“foo”(实际上是 OAuth token )的字符串加密 key public function encrypt( $text ) { // a
我是一名优秀的程序员,十分优秀!