質問

I have a JSON array which contains objects such as this:

{
    "bjones": {
        "fname": "Betty",
        "lname": "Jones",
        "password": "ababab",
        "level": "manager"
    }
}

my User class has a username which would require the JSON object's key to be used. How would I get the key of my JSON object?

What I have now is getting everything and creating a new User object, but leaving the username null. Which is understandable because my JSON object does not contain a key/value pair for "username":"value".

Gson gson = new Gson();
JsonParser p = new JsonParser();
JsonReader file = new JsonReader(new FileReader(this.filename));
JsonObject result = p.parse(file).getAsJsonObject().getAsJsonObject("bjones");
User newUser = gson.fromJson(result, User.class);

// newUser.username = null
// newUser.fname = "Betty"
// newUser.lname = "Jones"
// newUser.password = "ababab"
// newUser.level = "manager"

edit: I'm trying to insert "bjones" into newUser.username with Gson, sorry for the lack of clarification

役に立ちましたか?

解決

Use entrySet to get the keys. Loop through the entries and create a User for every key.

JsonObject result = p.parse(file).getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entrySet = result.entrySet();
for(Map.Entry<String, JsonElement> entry : entrySet) {
    User newUser = gson.fromJson(p.getAsJsonObject(entry.getKey()), User.class);
    newUser.username = entry.getKey();
    //code...
}

他のヒント

Using keySet() directly excludes the necessity in iteration:

ArrayList<String> objectKeys =
  new ArrayList<String>(
    myJsonObject.keySet());

Your JSON is fairly simple, so even the manual sort of methods (like creating maps of strings etc for type) will work fine.

For complex JSONs(where there are many nested complex objects and lists of other complex objects inside your JSON), you can create POJO for your JSON with some tool like http://www.jsonschema2pojo.org/

And then just :

final Gson gson = new Gson();

final MyJsonModel obj = gson.fromJson(response, MyJsonModel.class);

// Just access your stuff in object. Example
System.out.println(obj.getResponse().getResults().get(0).getId());
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top