第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

解析 JSON 的通用方法

解析 JSON 的通用方法

慕森卡 2021-11-24 14:37:39
我有一個(gè) JSON 示例{    "data":"some string data",    "amount":200,    "amountCurrencyList":[        {"value":4000.0,"currency":"USD"},         {"value":100.0,"currency":"GBP"}    ]}以及當(dāng)前將其解析為基礎(chǔ)對象的映射字段的方法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 結(jié)構(gòu)可以更改。想法是有一個(gè)單獨(dú)的方法,理想情況下可以輕松提取所需的參數(shù),例如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 對象并將其轉(zhuǎn)換為所需的參數(shù)。但是當(dāng)我嘗試操作時(shí)List<MoneyValue>System.out.println(detailsObj.getAmountCurrencyList().get(0).getValue());我越來越Exception: java.util.LinkedHashMap cannot be cast to MoneyValue實(shí)際上是否有可能實(shí)現(xiàn)我想要的,而無需使用精確的參數(shù)對 TypeReference 進(jìn)行硬編碼TypeReference<HashMap<String, List<MoneyValue>>>?UPDpublic class MoneyValue {@NotNullprivate BigDecimal value;@NotNullprivate String currency;EventDetails 類public class SomeEventDetails extends BaseEventDetails implements EventDetails {private ArrayList<MoneyValue> amountCurrencyList;
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊

如果一組屬性(我的意思是輸入數(shù)據(jù)的結(jié)構(gòu))是不可修改的,我們可以將它表示為一個(gè) 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;

  }

}

如您所見,這是一個(gè)deserializeMoneyValue注釋為 JSON 屬性的方法。因此,對于 ObjectMapper,它將用作自定義反序列化器。getValue方法是必要的,因?yàn)?Jackson 以這種方式工作,因此值將在滿足值大小的類中反序列化。例如,如果 value = "100" 它將被反序列化為Integer,如果 value = "100.0" -Double等等。其實(shí)這個(gè)方法你可以制作static并移動(dòng)到一些util類中??偨Y(jié)一下,您可以buildDetailsFromJson通過以下方式進(jìn)行更改:


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());

        }

    }

}


查看完整回答
反對 回復(fù) 2021-11-24
  • 1 回答
  • 0 關(guān)注
  • 199 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)