Parsowanie JSON

0

Moje DemoApplication wygląda następująco:

@SpringBootApplication
public class DemoApplication {
	@SneakyThrows
	public static void main(String[] args) {
		String GET_URL = "http://api.nbp.pl/api/exchangerates/tables/a/";
		URL url = new URL(GET_URL);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setRequestMethod("GET");
		int responseCode = httpURLConnection.getResponseCode();
		if (responseCode == HttpURLConnection.HTTP_OK){
			BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null){
				response.append(inputLine);
			}in.close();

			JSONArray obj = new JSONArray(response.toString());
			String jason = String.valueOf(obj);
			System.out.println(obj);
			ObjectMapper mapper = new ObjectMapper();
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			List<Rates> participantJsonList = mapper.readValue(jason, new TypeReference<List<Rates>>(){});
			System.out.println(participantJsonList.size());
			System.out.println(participantJsonList.get(0).mid);

		}
	}

Tak wygląda Rates:

@Getter
@Setter
@NoArgsConstructor
public class Rates {
    String currency;
    String mid;
    String code;
}

Zwraca mi:

[{"no":"011/A/NBP/2023","rates":[{"code":"THB","mid":0.1311,"currency":"bat (Tajlandia)"},{"code":"USD","mid":4.3398,"currency":"dolar amerykański"},{"code":"AUD","mid":3.0164,"currency":"dolar australijski"},{"code":"HKD","mid":0.5551,"currency":"dolar Hongkongu"},{"code":"CAD","mid":3.2321,"currency":"dolar kanadyjski"},{"code":"NZD","mid":2.7753,"currency":"dolar nowozelandzki"},{"code":"SGD","mid":3.2795,"currency":"dolar singapurski"},{"code":"EUR","mid":4.6946,"currency":"euro"},{"code":"HUF","mid":0.011763,"currency":"forint (Węgry)"},{"code":"CHF","mid":4.7005,"currency":"frank szwajcarski"},{"code":"GBP","mid":5.2992,"currency":"funt szterling"},{"code":"UAH","mid":0.1258,"currency":"hrywna (Ukraina)"},{"code":"JPY","mid":0.033697,"currency":"jen (Japonia)"},{"code":"CZK","mid":0.1956,"currency":"korona czeska"},{"code":"DKK","mid":0.6311,"currency":"korona duńska"},{"code":"ISK","mid":0.030386,"currency":"korona islandzka"},{"code":"NOK","mid":0.4373,"currency":"korona norweska"},{"code":"SEK","mid":0.4161,"currency":"korona szwedzka"},{"code":"RON","mid":0.9521,"currency":"lej rumuński"},{"code":"BGN","mid":2.4003,"currency":"lew (Bułgaria)"},{"code":"TRY","mid":0.231,"currency":"lira turecka"},{"code":"ILS","mid":1.2682,"currency":"nowy izraelski szekel"},{"code":"CLP","mid":0.005275,"currency":"peso chilijskie"},{"code":"PHP","mid":0.0792,"currency":"peso filipińskie"},{"code":"MXN","mid":0.2311,"currency":"peso meksykańskie"},{"code":"ZAR","mid":0.2535,"currency":"rand (Republika Południowej Afryki)"},{"code":"BRL","mid":0.843,"currency":"real (Brazylia)"},{"code":"MYR","mid":1.0031,"currency":"ringgit (Malezja)"},{"code":"IDR","mid":0.00028617,"currency":"rupia indonezyjska"},{"code":"INR","mid":0.053076,"currency":"rupia indyjska"},{"code":"KRW","mid":0.003504,"currency":"won południowokoreański"},{"code":"CNY","mid":0.6406,"currency":"yuan renminbi (Chiny)"},{"code":"XDR","mid":5.8537,"currency":"SDR (MFW)"}],"table":"A","effectiveDate":"2023-01-17"}]
1
null

Nie wiem, co robię nie tak. Podsuniecie jakiś pomysł? Z góry dzięki.

1

No ale w tym JSON'ie nie masz List<Rates>. Masz też nadrzędny obiekt, powinieneś zrobić bardziej coś

class Parent {
  String no;
  List<Rate> rates;
}

public class Rates {
    String currency;
    String mid;
    String code;
}

i próbować rozparsować List<Parent>

0

Riddle, zrobiłem to co napisałeś i teraz mam coś takiego: (Nie rozumiem jeszcze o co mu chodzi)

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `com.example.demo.Parent` from Array value (token `JsonToken.START_ARRAY`)
 at [Source: (String)"[{"no":"011/A/NBP/2023","rates":[{"code":"THB","mid":0.1311,"currency":"bat (Tajlandia)"},{"code":"USD","mid":4.3398,"currency":"dolar amerykański"},{"code":"AUD","mid":3.0164,"currency":"dolar australijski"},{"code":"HKD","mid":0.5551,"currency":"dolar Hongkongu"},{"code":"CAD","mid":3.2321,"currency":"dolar kanadyjski"},{"code":"NZD","mid":2.7753,"currency":"dolar nowozelandzki"},{"code":"SGD","mid":3.2795,"currency":"dolar singapurski"},{"code":"EUR","mid":4.6946,"currency":"euro"},{"code":"H"[truncated 1502 chars]; line: 1, column: 1]
	at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
	at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1746)
	at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1520)
	at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1467)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:650)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:211)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:187)
	at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:323)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4730)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3677)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3645)
	at com.example.demo.DemoApplication.main(DemoApplication.java:38)
0

Po zmianie kod wygląda tak:

    @SpringBootApplication
    public class DemoApplication {
	@SneakyThrows
	public static void main(String[] args) {
		String GET_URL = "http://api.nbp.pl/api/exchangerates/tables/a/";
		URL url = new URL(GET_URL);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setRequestMethod("GET");
		int responseCode = httpURLConnection.getResponseCode();
		if (responseCode == HttpURLConnection.HTTP_OK){
			BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();
			while ((inputLine = in.readLine()) != null){
				response.append(inputLine);
			}in.close();

			JSONArray obj = new JSONArray(response.toString());
			String jason = String.valueOf(obj);
			System.out.println(obj);
			ObjectMapper mapper = new ObjectMapper();
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			Parent participantJsonList = mapper.readValue(jason, Parent.class);
			System.out.println(participantJsonList.getRates().get(0).mid);
		}
	}

Parent.class:

@Getter
@Setter
@NoArgsConstructor
public class Parent {
    String no;
    List<Rates> rates;
}

Rates niezmienione. Dzięki za wszelkie tipy...

1

@fafikowski: List<Parent>, tak samo jak wcześniej, z TypeReference.

0
Riddle napisał(a):

@fafikowski: List<Parent>, tak samo jak wcześniej, z TypeReference.

Działa faktycznie.
Dałem:

List<Parent> participantJsonList = mapper.readValue(jason, new TypeReference<List<Parent>>(){});

Riddle, mega wdzięczność, poszło :) Niech Ci się wiedzie Bracie!

1 użytkowników online, w tym zalogowanych: 0, gości: 1