gpt4 book ai didi

java - 如何将字符串转换为 JSON,然后从 JSON 对象中提取所需的值?

转载 作者:行者123 更新时间:2023-11-30 03:44:11 25 4
gpt4 key购买 nike

我有一个如下字符串,我想将其转换为 JSON 对象,然后提取“text”字段的所有值:

{
"id": "/m/030qb3t",
"property": {
"/travel/travel_destination/tourist_attractions": {
"valuetype": "object",
"values": [
{
"text": "Hollywood Wax Museum",
"lang": "en",
"id": "/m/07_dsf",
"creator": "/user/rumifield",
"timestamp": "2008-12-27T17:02:32.000Z"
},
{
"text": "Hollywood Walk of Fame",
"lang": "en",
"id": "/m/0qjfl",
"creator": "/user/rumifield",
"timestamp": "2008-12-27T17:02:32.000Z"
},
{
"text": "TCL Chinese Theatre",
"lang": "en",
"id": "/m/04n2h_",
"creator": "/user/rumifield",
"timestamp": "2008-12-27T17:02:32.000Z"
},
{
"text": "Museum of Tolerance",
"lang": "en",
"id": "/m/04by8k",
"creator": "/user/rumifield",
"timestamp": "2008-12-27T17:02:32.001Z"
},
{
"text": "Getty Center",
"lang": "en",
"id": "/m/01mvl6",
"creator": "/user/rumifield",
"timestamp": "2008-12-27T17:02:32.001Z"
},
{
"text": "Museum of Contemporary Art, Los Angeles",
"lang": "en",
"id": "/m/02816j",
"creator": "/user/rumifield",
"timestamp": "2008-12-27T17:02:32.001Z"
},
{
"text": "Griffith Park",
"lang": "en",
"id": "/m/02sdph",
"creator": "/user/rumifield",
"timestamp": "2008-12-27T17:02:32.001Z"
},
{
"text": "Hollywood Boulevard",
"lang": "en",
"id": "/m/035zpq",
"creator": "/user/rumifield",
"timestamp": "2008-12-27T17:02:32.002Z"
},
{
"text": "Olvera Street",
"lang": "en",
"id": "/m/030svs",
"creator": "/user/rumifield",
"timestamp": "2008-12-27T17:02:32.002Z"
},
{
"text": "Centinela Adobe",
"lang": "en",
"id": "/m/04drm4",
"creator": "/user/supergmackenz",
"timestamp": "2011-12-13T18:45:26.003Z"
}
],
"count": 27.0
}
}
}

我已经尝试过

JsonParser jsParser = new JsonParser();
JsonObject jsObject = (JsonObject)jsParser.parse(jsonStr);
String text=jsObject.getString("text");

但它不起作用,我不知道如何提取所有“文本”值,任何帮助将不胜感激,谢谢!

最佳答案

所以首先你需要了解在JSON中你需要从上到下访问值,而不是直接访问键。我想这会做你想要的
这是针对 2.3 gson 库的

JsonParser jsParser = new JsonParser();
JsonObject jsObject = (JsonObject)jsParser.parse(jsonStr);
JsonObject property = jsObject.getAsJsonObject("property");
JsonObject tourist = property.getAsJsonObject("/travel/travel_destination/tourist_attractions");
JsonArray values = tourist.getAsJsonArray("values");
for(int i=0;i<values.size();i++) {
JsonObject data = values.get(i).getAsJsonObject();
String text = data.get("text").getAsString();
}

我希望我的回答足够清楚。如果您对我的回答有任何疑问,请随时在评论中提问:)

关于java - 如何将字符串转换为 JSON,然后从 JSON 对象中提取所需的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26153696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com