使用GSON获取JSON密钥名称

使用GSON获取JSON密钥名称

本文介绍了使用GSON获取JSON密钥名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  {
bjones:{
fname:Betty,
lname:Jones,
密码:ababab,
等级:经理
}
}

我的User类有一个用户名,它需要JSON对象的键用过的。我怎么会得到我的JSON对象的关键?



现在我得到的都是创建一个新的用户对象,但留下用户名为空。这是可以理解的,因为我的JSON对象不包含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

编辑:
我试图用Gson在newUser.username中插入bjones,对于没有澄清的问题抱歉

获得钥匙。循环访问条目并为每个键创建一个用户。

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


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...
}

这篇关于使用GSON获取JSON密钥名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:37