0

Пока разбираюсь именно с Jersey, поэтому не предлагайте другие библиотеки.

Итак, хочу получать с сайта курсы валют (НБУ) и превращать их в объекты.

Сразу оговорюсь, что в формате XML все работает. Не работает именно JSON. Образец взял отсюда.

package misc.jersey;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

import java.util.List;

public class CurrenciesJSON {

    public static void main(String[] args) {
        ClientConfig clientConfig = new DefaultClientConfig();

        // Create Client based on Config
        Client client = Client.create(clientConfig);

        WebResource webResource = client.resource("https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?json");

        Builder builder = webResource.accept(MediaType.APPLICATION_JSON) //
                .header("content-type", MediaType.APPLICATION_JSON);

        ClientResponse response = builder.get(ClientResponse.class);

        // Status 200 is successful.
        if (response.getStatus() != 200) {
            System.out.println("Failed with HTTP Error code: " + response.getStatus());
            String error = response.getEntity(String.class);
            System.out.println("Error: " + error);
            return;
        }

        GenericType<List<Currency>> generic = new GenericType<List<Currency>>() {
            // No thing
        };

        List<Currency> list = response.getEntity(generic);

        System.out.println("Output from Server .... \n");

        for (Currency currency : list) {
            System.out.println("-------------------------------------");
            System.out.println(currency);
        }
    }
}

Entity

package misc.jersey;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement()
@XmlAccessorType(XmlAccessType.FIELD)
public class Currency {
    private int r030;
    private String txt;
    private double rate;
    private String cc;
    private String exchangedate;

    public Currency() {
    }

    @Override
    public String toString() {
        return "Currency{" +
                "r030=" + r030 +
                ", txt='" + txt + '\'' +
                ", rate=" + rate +
                ", cc='" + cc + '\'' +
                ", exchangedate=" + exchangedate +
                '}';
    }
}

Exception: Exception in thread "main" javax.ws.rs.WebApplicationException: javax.xml.bind.UnmarshalException - with linked exception: [com.sun.istack.internal.SAXParseException2; lineNumber: 3; columnNumber: 10; unexpected element (uri:"", local:"r030"). Expected elements are <{}currency>] at com.sun.jersey.core.provider.jaxb.AbstractListElementProvider.readFrom(AbstractListElementProvider.java:355) etc...

Если поменять адрес запроса на https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?xml и в заголовке на MediaType.APPLICATION_XML, то работает!

В чем проблема? Что за unexpected element (uri:"", local:"r030")?

13
  • Аргументы за минус? Или ты - бот?
    – user224616
    20 ноя 2018 в 11:53
  • в ошибке же написано, что вместо ожидаемого поля currency на вход парсеру приходит r030, проверьте свои POJO классы в модели
    – mit
    20 ноя 2018 в 12:18
  • В модели не может быть причина, т.к. с xml отрабатывает нормально
    – user224616
    20 ноя 2018 в 12:33
  • попробуйте убрать в модели JAXB аннотации @XmlRootElement() и @XmlAccessorType(XmlAccessType.FIELD)
    – mit
    20 ноя 2018 в 13:10
  • 1
    я бы рекомендовал вам, сразу, начать изучение jersey со 2 версии. Ваш пример по 1 версии. Между ними, насколько я помню большие различия.
    – mit
    22 ноя 2018 в 6:22

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.