簡體   English   中英

我無法從 json 文件中讀取和打印值

[英]I can't read and print values from json file

所以我試圖在 JAVA 控制台中將 json 文件作為字符串讀取和打印。 程序不是打印 json 內容,而是打印參考 class 的默認屬性值。 我該如何解決這個問題? 我的代碼是這樣的

public class test {

 

       private static final String WEATHER_URL = "https://api.collectapi.com/weather/getWeather?data.lang=tr&data.city=istanbul";
    
        public static void main(String[] args) throws IOException, InterruptedException {
    
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = (HttpRequest) HttpRequest.newBuilder()
                    .GET()
                    .header("content-type", "application/json")
                    .header("authorization", "apikey myapikey")
                    .uri(URI.create(WEATHER_URL))
                    .build();
    
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());




//parse JSON into objects 
    
    
    ObjectMapper mapper = new ObjectMapper();
    
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.setVisibility(VisibilityChecker.Std.defaultInstance().withFieldVisibility(JsonAutoDetect.Visibility.ANY));

List<Data>data = mapper.readValue(response.body(), new TypeReference<List<Data>>() { });


   
        System.out.println(data);

//CONSOLE OUTPUT
[Data{date=null, day=null, icon=null, description=null, status=null, degree=0.0, min=0.0, max=0.0, night=0.0, humidity=0}]
------------------------------------------------------------------------
BUILD SUCCESS

//數據 CLASS

public class Data {
  
  

      private String date;
        private String day ; 
        private String icon ; 
        private String description;
        private String status ;
        private double degree;
        private double min;
        private double max ; 
        private double night ; 
        private int humidity;

//getter 和 setter 在這里

@Override
    public String toString() {
        return "Data{" + "date=" + date + ", day=" + day + ", icon=" + icon + ", description=" + description + ", status=" + status + ", degree=" + degree + ", min=" + min + ", max=" + max + ", night=" + night + ", humidity=" + humidity + '}';
    }

//JSON文件結構是這樣的

{
  "result": [
    {
      "date": "24.09.2018",
      "day": "Pazartesi",
      "icon": "https://image.flaticon.com/icons/svg/143/143769.svg",
      "description": "açık",
      "status": "Clear",
      "degree": "31",
      "min": "11.6",
      "max": "31",
      "night": "11.6",
      "humidity": "17"
    },
    {
      "date": "25.09.2018",
      "day": "Salı",
      "icon": "https://image.flaticon.com/icons/svg/143/143769.svg",
      "description": "yağmurlu",
      "status": "Rainy",
      "degree": "24.14",
      "min": "7.63",
      "max": "25.82",
      "night": "9.09",
      "humidity": "35"
    },
    "..."
  ]
}

將 Apache 常用工具添加到 pom 中,它會像魅力一樣工作

import org.apache.commons.io.IOUtils; 
    
    

String theJsonString = ""; 
    
     
 
 theJsonString=IOUtils.toString(classLoader.getResourceAsStream("/path/file.json"));

您解析響應的方式對我來說似乎是錯誤的。 JSON 文件結構響應不是以 JSONArray 開頭,實際的 JSON 響應是一個 object ,它有一個名為result的鍵,它是JSONObject的數組,所以下面的行不會起作用

List<Data>data = mapper.readValue(response.body(), new TypeReference<List<Data>>() { });

response.body()沒有返回一個數組,它是一個 object,所以如果你想從響應中獲取數組,你需要先得到result ,然后你才能解析數組。

您可能需要先更新 POJO:

    public class Response {
        private Data result;
    }

    class Data {
        private String date;
        private String day ;
        private String icon ;
        private String description;
        private String status ;
        private double degree;
        private double min;
        private double max ;
        private double night ;
        private int humidity;
    }

然后像這樣的東西可以解析:

final Response response = mapper.readValue(response.body(), new TypeReference<Response>() { });
final List<Data> data = response.result

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM