gpt4 book ai didi

java - 打印 JSON 值

转载 作者:行者123 更新时间:2023-12-01 13:50:40 24 4
gpt4 key购买 nike

这只是我需要访问的一段 JSON 代码...

"forecast":{
"txt_forecast": {
"date":"8:00 AM MST",
"forecastday": [
{
"period":0,
"icon":"partlycloudy",
"icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",
"title":"Thursday",
"fcttext":"Partly cloudy. High of 63F. Winds less than 5 mph.",
"fcttext_metric":"Partly cloudy. High of 17C. Winds less than 5 km/h.",
"pop":"0"
}

我在打印嵌套 JSON 值时遇到问题。如果我想打印“fcttext”,我该怎么做?我已经尝试过这个...

public static void display() {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("C:\\ABC.json"));

JSONObject jsonObject = (JSONObject) obj;
String a = (String) jsonObject.get("forecast").toString();
System.out.println(a);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (ParseException e) {
e.printStackTrace();
}
}

我做错了什么? Full JSON code .

最佳答案

首先你的json格式不正确,使用jsonlint[1]检查你的json格式是否正确。

将 JSON 重新格式化为以下格式,

{
"forecast": {
"txt_forecast": {
"date": "8: 00AMMST",
"forecastday": [
{
"period": 0,
"icon": "partlycloudy",
"icon_url": "http: //icons-ak.wxug.com/i/c/k/partlycloudy.gif",
"title": "Thursday",
"fcttext": "Partlycloudy.Highof63F.Windslessthan5mph.",
"fcttext_metric": "Partlycloudy.Highof17C.Windslessthan5km/h.",
"pop": "0"
}
]
}
}
}

使用以下代码进行解析,

package com.aamir.stackoverflow;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class JSONParserStackOverflow {
public static void main(String[] args) {

String request = "{\n" +
" \"forecast\": {\n" +
" \"txt_forecast\": {\n" +
" \"date\": \"8: 00AMMST\",\n" +
" \"forecastday\": [\n" +
" {\n" +
" \"period\": 0,\n" +
" \"icon\": \"partlycloudy\",\n" +
" \"icon_url\": \"http: //icons-ak.wxug.com/i/c/k/partlycloudy.gif\",\n" +
" \"title\": \"Thursday\",\n" +
" \"fcttext\": \"Partlycloudy.Highof63F.Windslessthan5mph.\",\n" +
" \"fcttext_metric\": \"Partlycloudy.Highof17C.Windslessthan5km/h.\",\n" +
" \"pop\": \"0\"\n" +
" }\n" +
" ]\n" +
" }\n" +
" }\n" +
"}";

JsonElement weatherJSON = new JsonParser().parse(request);
JsonObject weatherObj = weatherJSON.getAsJsonObject();
JsonObject forecastObj = weatherObj.get("forecast").getAsJsonObject();
JsonObject txt_forecast = forecastObj.get("txt_forecast").getAsJsonObject();

JsonArray forecastDays = txt_forecast.getAsJsonArray("forecastday");


for(JsonElement forecastDay : forecastDays) {
System.out.println(forecastDay.getAsJsonObject().get("fcttext").toString());
}
}
}

我使用了 Google 的 GSON[2] 库来解析 JSON。

[1] http://jsonlint.com/

[2] https://code.google.com/p/google-gson/

关于java - 打印 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19986728/

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