繁体   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