【问题标题】:I can't read and print values from json file我无法从 json 文件中读取和打印值
【发布时间】:2021-01-17 11:52:00
【问题描述】:

所以我试图在 JAVA 控制台中将 json 文件作为字符串读取和打印。程序不是打印 json 内容,而是打印引用类的默认属性值。我该如何解决这个问题?我的代码是这样的

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

//数据类

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"
    },
    "..."
  ]
}

【问题讨论】:

    标签: java json deserialization httpclient objectmapper


    【解决方案1】:

    将 Apache 常用工具添加到 pom 中,它会像魅力一样工作

    import org.apache.commons.io.IOUtils; 
        
        
    
    String theJsonString = ""; 
        
         
     
     theJsonString=IOUtils.toString(classLoader.getResourceAsStream("/path/file.json"));
    

    【讨论】:

      【解决方案2】:

      您解析响应的方式对我来说似乎是错误的。 JSON 文件结构响应不是以 JSONArray 开头,实际的 JSON 响应是一个对象,它有一个名为 result 的键,它是一个 JSONObject 的数组,所以下面的行在这里不起作用。

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

      response.body() 不返回数组,它是一个对象,所以如果你想从响应中获取数组,你需要先获取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
      

      【讨论】:

      • 我如何访问结果? response.result 不起作用。我们是在谈论 Response 类的领域吗?
      猜你喜欢
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 2022-08-13
      相关资源
      最近更新 更多