【问题标题】:How to extract information from API Response in Java如何从 Java 中的 API 响应中提取信息
【发布时间】:2022-08-13 21:10:43
【问题描述】:

我对 Java 很陌生,我偶然发现了以下问题。我想从 API 响应中提取信息,如下所示:

{\"data\":{\"52WeekChange\":-0.23800159,\"SandP52WeekChange\":-0.0445475,\"address1\":\"Salesforce Tower\".....

我需要提取的是 address1 信息。有人有什么想法吗?

  • 创建一个具有相同属性/变量的 POJO 类,并使用 com.fasterxml.jackson 库将 json 响应转换为您的 POJO 类。或者您可以使用 org.json 库将 JSON 字符串简单地转换为 JSON 对象。
  • API 响应似乎是 JSON。有几个 Java libraries 用于处理 JSON。选择一个库,学习如何使用它,您应该能够自己发现问题的答案。
  • @maddy23285 请将您的评论更改为答案,以便我标记它。

标签: java


【解决方案1】:

去阅读杰克逊图书馆: https://github.com/FasterXML/jackson

您需要创建一个对象来模拟您正在摄取的 JSON。然后,您将使用 Jackson 将该 JSON 响应转换为 java 对象,您可以在其中正常使用它。

教程: https://www.tutorialspoint.com/jackson/index.htm

例子: https://www.tutorialspoint.com/jackson/jackson_object_serialization.htm

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonTester {
   public static void main(String args[]){
      JacksonTester tester = new JacksonTester();
      try {
         Student student = new Student();
         student.setAge(10);
         student.setName("Mahesh");
         tester.writeJSON(student);

         Student student1 = tester.readJSON();
         System.out.println(student1);

      } catch (JsonParseException e) {
         e.printStackTrace();
      } catch (JsonMappingException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{
      ObjectMapper mapper = new ObjectMapper(); 
      mapper.writeValue(new File("student.json"), student);
   }

   private Student readJSON() throws JsonParseException, JsonMappingException, IOException{
      ObjectMapper mapper = new ObjectMapper();
      Student student = mapper.readValue(new File("student.json"), Student.class);
      return student;
   }
}

class Student {
   private String name;
   private int age;
   public Student(){}
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public String toString(){
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2017-10-12
    • 2021-05-26
    • 2015-05-25
    • 2015-06-02
    • 1970-01-01
    相关资源
    最近更新 更多