簡體   English   中英

解析JSON的通用方法

[英]Generic way to parse JSON

我有一個JSON示例

{
    "data":"some string data",
    "amount":200,
    "amountCurrencyList":[
        {"value":4000.0,"currency":"USD"}, 
        {"value":100.0,"currency":"GBP"}
    ]
}

當前將其解析為基礎對象的地圖字段的方法和方法

public void buildDetailsFromJson(String details) {
    if (details != null) {
        TypeReference<HashMap<String, Object>> mapTypeReference = new TypeReference<HashMap<String, Object>>() {
        };
        ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
            mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
            detailsMap = mapper.readValue(details, mapTypeReference);
        } catch (IOException e) {
            log.error("Exception during JSON {} parsing! {}", details, e.getMessage());
        }
    }
}

JSON結構可以更改。 想法是有一個單獨的方法,理想情況下可以輕松提取所需的參數,例如map.get(key_name)

例如

public void setUpFieldsFromMap() {
    HashMap<String, Object> map = super.detailsMap;
    this.amountCurrencyList = (ArrayList<MoneyValue>) map.get("amountCurrencyList");
    if (isNull(amountCurrencyList)) {
        throw new InvalidOrMissingParametersException("Exception during JSON parsing! Critical data is missing in DetailsMap - " + map.toString());
    }
}

因此,通過鍵獲取List對象並將其轉換為所需的參數。 但是當我嘗試使用List<MoneyValue>

System.out.println(detailsObj.getAmountCurrencyList().get(0).getValue());

我越來越

Exception: java.util.LinkedHashMap cannot be cast to MoneyValue

實際上,無需使用諸如TypeReference<HashMap<String, List<MoneyValue>>>類的確切參數對TypeReference進行硬編碼,實際上是否可以實現我想要的?

UPD

public class MoneyValue {
@NotNull
private BigDecimal value;
@NotNull
private String currency;

EventDetails類

public class SomeEventDetails extends BaseEventDetails implements EventDetails {

private ArrayList<MoneyValue> amountCurrencyList;

@Override
public void setUpFieldsFromMap() {
    HashMap<String, Object> map = super.detailsMap;
    this.amountCurrencyList = (ArrayList<MoneyValue>) map.get("amountCurrencyList");
    if (isNull(amountCurrencyList)) {
        throw new InvalidOrMissingParametersException("Exception during JSON parsing! Critical data is missing in DetailsMap - " + map.toString());
    }
}

}

如果一組屬性(我的意思是輸入數據的結構)不可修改,我們可以將其表示為POJO類。 使其成為DetailsData

public class DetailsData {
  private String data;
  private BigDecimal amount;
  private List<MoneyValue> amountCurrencyList;

  /*getters, setters, constructors*/

  public DetailsData() {
  }

  @JsonProperty("amountCurrencyList")
  private void deserializeMoneyValue(List<Map<String, Object>> data) {
    if (Objects.isNull(amountCurrencyList)) {
        amountCurrencyList = new ArrayList<>();
    } else {
        amountCurrencyList.clear();
    }        
    MoneyValue moneyValue;
    for (Map<String, Object> item : data) {
      moneyValue = new MoneyValue(getValue(item.get("value")),
          (String) item.get("currency"));
      amountCurrencyList.add(moneyValue);
    }
  }

  private BigDecimal getValue(Object value) {
    BigDecimal result = null;
    if (value != null) {
      if (value instanceof BigDecimal) {
        result = (BigDecimal) value;
      } else if (value instanceof BigInteger) {
        result = new BigDecimal((BigInteger) value);
      } else if (value instanceof Number) {
        result = new BigDecimal(((Number) value).doubleValue());
      } else {
        throw new ClassCastException("Invalid value");
      }
    }
    return result;
  }
}

正如你可以看到這里有一個方法deserializeMoneyValue標注為JSON屬性。 因此,對於ObjectMapper,它將用作自定義反序列化器。 getValue方法是必需的,因為Jackson是以這種方式工作的,因此該值將在滿足該值大小的類中反序列化。 例如,如果value =“ 100”,則將反序列化為Integer ;如果value =“ 100.0”,則將反序列化為Double ,依此類推。 實際上,您可以使此方法static並移入某些util類。 總結一下,您可以按以下方式更改buildDetailsFromJson

public void buildDetailsFromJson(String details) {
    if (details != null) {        
        ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
            mapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
            // assuming the eventDetails is an instance of DetailsData
            eventDetails = mapper.readValue(details, DetailsData.class);
        } catch (IOException e) {
            log.error("Exception during JSON {} parsing! {}", details, e.getMessage());
        }
    }
}

和EventDetail類:

public class SomeEventDetails extends BaseEventDetails implements EventDetails {

    private List<MoneyValue> amountCurrencyList;

    @Override
    public void setUpFieldsFromMap() {
        this.amountCurrencyList = super.eventDetails.getAmountCurrencyList();
        if (isNull(amountCurrencyList)) {
            throw new InvalidOrMissingParametersException("Exception during JSON parsing! Critical data is missing in DetailsMap - " + super.eventDetails.toString());
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM