简体   繁体   中英

Converting special JSON response using retrofit

I'm trying to convert a specific JSON object that has a variable amount of subobjects, feks:

{
   name: 'Lars Monsen'
   id: 192492384
   accounts: {
        testaccount: {...}
        testaccount2: {...}
        ....
   }
}

So its easy to convert all the fields except for accounts. Since I don't know how many accounts each person has and accounts isn't a list. How can I map this info as an object?

The objects inside the account objects are the same. But since accounts not a list and the names of the accounts varies, I don't know how to map this properly.

Is it possible to write a specific converter for just accounts? I tried to write a specific converter but that ended up only the whole object.

class Response {
    String name;
    long id;
    List<Account> accounts;
}

// ..

public class AccountsConverter implements JsonDeserializer<List<Account>> {
    public List<Account> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
        List<Account> vals = new ArrayList<Account>();
        for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            Account account = ctx.deserialize(entry.getValue(), Account.class);
            account.setName(entry.getKey());
            vals.add(account);
        }
        return vals;
    }
}

As you can see, I implemented a custom converter for List<Account> , even though account in your json is actually an object. I iterate over every entry (key-value pair) in this JsonObject and deserialize the value. After that I append the key to the account instance using a setter.

To properly register this converter use this:

gsonBuilder.registerTypeAdapter(new TypeToken<List<Account>>(){}.getType(), new AccountsConverter());

Since accounts is a JS object with a fixed value type, why not use a Map with fixed value type? Like so

class Data {
    String name;
    int id;
    Map<String, Account> accounts;
}

class Account {
    ...
}

Just tested it with Gson, and it works. The map generated by Gson is even a LinkedHashMap, so the order of entries is preserved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM