JtecX
JtecX

Reputation: 107

Gson Help - Trying to get the first value (key) of JSON using Gson

Trying to get the fist value (key) of JSON using Gson lib, any help is good. Looking to get -K_63RGSCZra1jVeDrmT from the JSON and want to save it in String variable.

Here is mine code and output :

gson.toJson(dataSnapshot.getValue());
Log.d(tag, "gson: " + gson.toJson(dataSnapshot.getValue()));

output:

{"-K_63RGSCZra1jVeDrmT":{"name":"Joseph witman","email":"[email protected]"}}

Upvotes: 1

Views: 2241

Answers (2)

atiqkhaled
atiqkhaled

Reputation: 386

Here is your code to get key :

    JsonParser parser = new JsonParser();
    JsonObject jobj = parser.parse(new FileReader("Filepath_JSON")).getAsJsonObject();

    Gson gson = new Gson();
    Set<Map.Entry<String, JsonElement>> entrySet = jobj.entrySet();
    for(Map.Entry<String, JsonElement> entry : entrySet) {
        Person prsn = gson.fromJson(jobj.getAsJsonObject(entry.getKey()), Person.class);
        prsn.setId(entry.getKey());
        System.out.println("id :  " + prsn.getId());

    }

Here is Pojo Person class :

class Person {

private String id;
private String name;
private String email;


public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
} }

I run the code and it works fine.

Cheers.

Upvotes: 2

Jyr
Jyr

Reputation: 711

You could try

String json = "{\"-K_63RGSCZra1jVeDrmT\":{\"name\":\"Joseph witman\",\"email\":\"[email protected]\"}}";
JsonParser jp = new JsonParser();
JsonElement element = jp.parse(json);
JsonObject root = element.getAsJsonObject();

Since JsonObject.entrySet() contains all key values you could extract them in the following way;

for (Entry<String, JsonElement> e : root.entrySet()) {
    System.out.println(e.getKey());
}

Upvotes: 2

Related Questions