Java 使用 GSON 获取 JSON 密钥名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22358243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get JSON key name using GSON
提问by Ahmad
I have a JSON array which contains objects such as this:
我有一个 JSON 数组,其中包含这样的对象:
{
"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?
我的 User 类有一个用户名,需要使用 JSON 对象的密钥。我将如何获得我的 JSON 对象的密钥?
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".
我现在拥有的是获取所有内容并创建一个新的 User 对象,但将用户名留空。这是可以理解的,因为我的 JSON 对象不包含“用户名”:“值”的键/值对。
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
编辑:我正在尝试使用 Gson 将“bjones”插入到 newUser.username 中,抱歉缺乏说明
采纳答案by Max Meijer
Use entrySetto get the keys. Loop through the entries and create a User for every key.
使用entrySet获取密钥。遍历条目并为每个键创建一个用户。
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...
}
回答by nishantbhardwaj2002
Your JSON is fairly simple, so even the manual sort of methods (like creating maps of strings etc for type) will work fine.
您的 JSON 相当简单,因此即使是手动排序的方法(例如为类型创建字符串映射等)也能正常工作。
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/
对于复杂的 JSON(其中 JSON 中有许多嵌套的复杂对象和其他复杂对象的列表),您可以使用诸如http://www.jsonschema2pojo.org/ 之类的工具为您的 JSON 创建 POJO
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());
回答by Zon
Using keySet()directly excludes the necessity in iteration:
直接使用keySet()就排除了迭代的必要性:
ArrayList<String> objectKeys =
new ArrayList<String>(
myJsonObject.keySet());