I´m pretty new to Java and I stumbled on a following problem. I would like to extract information from an API response as following:
{"data":{"52WeekChange":-0.23800159,"SandP52WeekChange":-0.0445475,"address1":"Salesforce Tower".....
What I would need to extract is the address1 information. Anyone any ideas?
CodePudding user response:
Go read about the Jackson library: https://github.com/FasterXML/jackson
You'll want to create an object that models the JSON you are ingesting. You'll then use Jackson to transform that JSON response into the java object, where you can work with it normally.
Tutorial: https://www.tutorialspoint.com/jackson/index.htm
Example: 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 " ]";
}
}