Springboot - конвертировать JSON в JAVA - PullRequest
0 голосов
/ 16 ноября 2018

Мне нужно получить курс обмена валют из оставшегося API в мое весеннее загрузочное приложение и преобразовать ответ JSON в класс Java. API даст мне ответ, как показано ниже: -

{
    "USD_INR": {
        "val": 71.884966
    }
}

Код показан ниже:

@RestController
public class MainController {

  @Autowired
  private RestTemplate restTemplate;

  @GetMapping("/hello")
  public float hello(){

     ExchangeRate exchangeRate = restTemplate.getForObject("https://free.currencyconverterapi.com/api/v6/convert?q=Source_Target&compact=y",ExchangeRate.class);
     return exchangeRate.getSource_Target().getVal();
  }
}

-

@JsonIgnoreProperties(ignoreUnknown = true)
public class ExchangeRate {
Source_Target SourceTargetObject;

  public Source_Target getSource_Target() {
      return SourceTargetObject;
  }


  public void setSource_Target(Source_Target SourceTargetObject) {
      this.SourceTargetObject = SourceTargetObject;
  }
}


@JsonIgnoreProperties(ignoreUnknown = true)
public class Source_Target {
private float val;

  public float getVal() {
    return val;
  }

  public void setVal(float val) {
    this.val = val;
  }
}

После выполнения вызова REST я получаю исключение NULL. Ничего не возвращается. Я не могу понять проблему здесь. Пожалуйста, помогите

Ответы [ 3 ]

0 голосов
/ 16 ноября 2018

Ваш класс ExchangeRate должен быть:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ExchangeRate {
    @JsonProperty("USD_INR")
    Source_Target SourceTargetObject;

    public Source_Target getSource_Target() {
        return SourceTargetObject;
    }

    public void setSource_Target(Source_Target SourceTargetObject) {
        this.SourceTargetObject = SourceTargetObject;
    }

Тогда ваш класс Source_Target должен быть:

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Source_Target {
    @JsonProperty("val")
    private float val;

    public float getVal() {
         return val;
    }

    public void setVal(float val) {
        this.val = val;
    }
}

Пожалуйста, остерегайтесь вашего соглашения об именах классов. Я бы переименовал Source_Target в SourceTarget, чтобы следовать соглашению об именах Java

0 голосов
/ 18 ноября 2018

Вы создаете пользовательскую карту:

public class ExchangeRate extends HashMap<String, ExchangeRateValue> implements Serializable {        
}

public class ExchangeRateValue implements Serializable {

    private float val;

    public float getVal() {
        return val;
    }

    public void setVal(float val) {
        this.val = val;
    }
}

И назовите это:

 ExchangeRate exchangeRate = restTemplate.getForObject("https://free.currencyconverterapi.com/api/v6/convert?q=Source_Target&compact=y", ExchangeRate.class);
 float data = exchangeRate.get("USD_INR").getVal();
0 голосов
/ 16 ноября 2018

Вы можете использовать jsonscheme2pojo для простой генерации Java-бинов из json.

JSON:

{
"USD_INR": {
    "val": 71.884966
}

}

Соответствующий Java-бин:

-----------------------------------com.example.Example.java-----------------------------------

package com.example;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"USD_INR"
})
public class Example implements Serializable
{

@JsonProperty("USD_INR")
private USDINR uSDINR;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private final static long serialVersionUID = -932753391825750904L;

@JsonProperty("USD_INR")
public USDINR getUSDINR() {
return uSDINR;
}

@JsonProperty("USD_INR")
public void setUSDINR(USDINR uSDINR) {
this.uSDINR = uSDINR;
}

public Example withUSDINR(USDINR uSDINR) {
this.uSDINR = uSDINR;
return this;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

public Example withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}

}
-----------------------------------com.example.USDINR.java-----------------------------------

package com.example;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"val"
})
public class USDINR implements Serializable
{

@JsonProperty("val")
private Double val;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private final static long serialVersionUID = -6384976748235176082L;

@JsonProperty("val")
public Double getVal() {
return val;
}

@JsonProperty("val")
public void setVal(Double val) {
this.val = val;
}

public USDINR withVal(Double val) {
this.val = val;
return this;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

public USDINR withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}

}
...