Commit 9af6e0fb by patryk

Parsowanie JSONa po raz pierwszy

parent 279664db
...@@ -33,6 +33,11 @@ ...@@ -33,6 +33,11 @@
<artifactId>commons-csv</artifactId> <artifactId>commons-csv</artifactId>
<version>1.11.0</version> <version>1.11.0</version>
</dependency> </dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.json</artifactId>
<version>2.0.1</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file
package pobieranie;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import jakarta.json.Json;
import jakarta.json.JsonArray;
import jakarta.json.JsonObject;
import jakarta.json.JsonReader;
import jakarta.json.JsonValue;
public class Pobieranie4_JSON {
public static void main(String[] args) {
final String adres = "http://api.nbp.pl/api/exchangerates/tables/A/?format=json";
try {
URI uri = new URI(adres);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(uri).build();
HttpResponse<InputStream> response = client.send(request, BodyHandlers.ofInputStream());
System.out.println("response: " + response);
System.out.println("status: " + response.statusCode());
System.out.println("Content-Type: " + response.headers().firstValue("content-type").orElse("--"));
if(response.statusCode() != 200) {
return;
}
// parsowanie JSONa z pomocą biblioteki Jakarta JSON (utworzone w Java EE 7 i dalej rozwijane)
// alternatywy: GSON, org.json, Jackson
JsonArray json;
try(JsonReader reader = Json.createReader(response.body())) {
json = reader.readArray();
} // tutaj już zamykamy połączenie
// zerowym (i jedynym) elementem tablicy jest {obiekt JSONowy} odpowiadający tabeli walut
JsonObject tabela = json.getJsonObject(0);
// bezpośrednio w tym obiekcie są takie pola, jak numer i data
System.out.println("Numer tabeli: " + tabela.getString("no"));
System.out.println("Data: " + tabela.getString("effectiveDate"));
// w polu rates znajduje się tablica zawierająca dane poszczególnych walut
JsonArray rates = tabela.getJsonArray("rates");
System.out.println("Liczba walut: " + rates.size());
System.out.println();
for(JsonValue rate : rates) {
// System.out.println(rate);
JsonObject rateObj = rate.asJsonObject();
String nazwa = rateObj.getString("currency");
String kod = rateObj.getString("code");
BigDecimal kurs = rateObj.getJsonNumber("mid").bigDecimalValue();
System.out.println(kod + " " + nazwa + ": " + kurs);
}
} catch (IOException | URISyntaxException | InterruptedException e) {
e.printStackTrace();
}
}
}
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package pogoda;
import jakarta.json.Json;
import jakarta.json.JsonObject;
import jakarta.json.JsonReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
/**
*
* @author kurs
*/
public class WyswietlPogodeDlaWspolrzednych extends javax.swing.JFrame {
/**
* Creates new form WyswietlPogodeDlaWspolrzednych
*/
public WyswietlPogodeDlaWspolrzednych() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jSpinner1 = new javax.swing.JSpinner();
jSpinner2 = new javax.swing.JSpinner();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel3 = new javax.swing.JLabel();
jLabel_Temperatura = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jSpinner1.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N
jSpinner1.setModel(new javax.swing.SpinnerNumberModel(52.0d, -90.0d, 90.0d, 1.0d));
jSpinner2.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N
jSpinner2.setModel(new javax.swing.SpinnerNumberModel(21.0d, -180.0d, 180.0d, 1.0d));
jLabel1.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N
jLabel1.setText("Szerokość geograficzna");
jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N
jLabel2.setText("Długość geograficzna");
jButton1.setFont(new java.awt.Font("Segoe UI", 1, 24)); // NOI18N
jButton1.setText("Pobierz pogodę");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N
jLabel3.setText("Temperatura");
jLabel_Temperatura.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
jLabel_Temperatura.setText("jLabel4");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSpinner2, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel_Temperatura, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(18, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jSpinner2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel_Temperatura, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(259, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
double lat = (Double)jSpinner1.getValue();
double lon = (Double)jSpinner2.getValue();
String adres = "https://api.open-meteo.com/v1/forecast?latitude=" + lat
+ "&longitude=" + lon
+ "&current_weather=true";
try {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(new URI(adres)).build();
HttpResponse<InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
JsonReader reader = Json.createReader(response.body());
JsonObject json = reader.readObject();
JsonObject weather = json.getJsonObject("current_weather");
double temperatura = weather.getJsonNumber("temperature").doubleValue();
jLabel_Temperatura.setText(String.valueOf(temperatura));
} catch (URISyntaxException | IOException | InterruptedException e) {
e.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(WyswietlPogodeDlaWspolrzednych.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(WyswietlPogodeDlaWspolrzednych.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(WyswietlPogodeDlaWspolrzednych.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(WyswietlPogodeDlaWspolrzednych.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new WyswietlPogodeDlaWspolrzednych().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel_Temperatura;
private javax.swing.JSpinner jSpinner1;
private javax.swing.JSpinner jSpinner2;
// End of variables declaration
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment