Get JSON key name using GSON

后端 未结 3 1752
名媛妹妹
名媛妹妹 2021-02-14 01:48

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

{
    \"bjones\": {
        \"fname\": \"Betty\",
        \"lname\": \"Jones\",
        \"password\": \         


        
相关标签:
3条回答
  • 2021-02-14 02:30

    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());
    
    0 讨论(0)
  • 2021-02-14 02:32

    Using keySet() directly excludes the necessity in iteration:

    ArrayList<String> objectKeys =
      new ArrayList<String>(
        myJsonObject.keySet());
    
    0 讨论(0)
  • 2021-02-14 02:46

    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...
    }
    
    0 讨论(0)
提交回复
热议问题