简体   繁体   中英

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":"jwitman@gmail.com"}}

You could try

String json = "{\"-K_63RGSCZra1jVeDrmT\":{\"name\":\"Joseph witman\",\"email\":\"jwitman@gmail.com\"}}";
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());
}

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.

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