简体   繁体   English

我无法从 json 文件中读取和打印值

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

So I'm trying to read and print the json file as a string in the JAVA console.所以我试图在 JAVA 控制台中将 json 文件作为字符串读取和打印。 Instead of printing json content, program is printing the default attribute values of reference class.程序不是打印 json 内容,而是打印参考 class 的默认属性值。 How can I resolve this problem?我该如何解决这个问题? My code is like this我的代码是这样的

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

//DATA CLASS //数据 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;

//getters and setters are here //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 FILE STRUCTURE IS LIKE THIS //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"
    },
    "..."
  ]
}

Add Apache common utils to pom and it will work like charm将 Apache 常用工具添加到 pom 中,它会像魅力一样工作

import org.apache.commons.io.IOUtils; 
    
    

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

The way you have parsed the response seems wrong to me.您解析响应的方式对我来说似乎是错误的。 JSON file structure response doesn't start with a JSONArray, the actual JSON response is an object which has a key named result which is an array of JSONObject , so the line below won't work here. JSON 文件结构响应不是以 JSONArray 开头,实际的 JSON 响应是一个 object ,它有一个名为result的键,它是JSONObject的数组,所以下面的行不会起作用

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

response.body() isn't returning an array it's an object, so if you want to get array out of the response you need to first get the result and then you can parse the array. response.body()没有返回一个数组,它是一个 object,所以如果你想从响应中获取数组,你需要先得到result ,然后你才能解析数组。

You may need to update the POJO first:您可能需要先更新 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;
    }

Then something like this can parse:然后像这样的东西可以解析:

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