Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSON key name using GSON

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

like image 437
Ahmad Avatar asked Mar 12 '14 16:03

Ahmad


People also ask

What is the difference between JSON and GSON?

The JSON format was originally specified by Douglas Crockford. On the other hand, GSON is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

What is JsonObject and JsonElement?

public final class JsonObject extends JsonElement. A class representing an object type in Json. An object consists of name-value pairs where names are strings, and values are any other type of JsonElement. This allows for a creating a tree of JsonElements.

How does GSON handle null values?

By default, the Gson object does not serialize the fields with null values to JSON. If a field in a Java object is null, Gson excludes it. We can force Gson to serialize null values via the GsonBuilder class. We need to call the serializeNulls() method on the GsonBuilder instance before creating the Gson object.


2 Answers

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...
}
like image 60
Max Meijer Avatar answered Sep 19 '22 05:09

Max Meijer


Using keySet() directly excludes the necessity in iteration:

ArrayList<String> objectKeys =
  new ArrayList<String>(
    myJsonObject.keySet());
like image 24
Zon Avatar answered Sep 23 '22 05:09

Zon