【问题标题】:Generic way to parse JSON解析 JSON 的通用方法
【发布时间】:2018-10-18 04:50:03
【问题描述】:

我有一个 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&lt;MoneyValue&gt; 进行操作时

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

我来了

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

如果不使用 TypeReference&lt;HashMap&lt;String, List&lt;MoneyValue&gt;&gt;&gt; 之类的确切参数对 TypeReference 进行硬编码,是否真的可以实现我想要的?

更新

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

}

【问题讨论】:

  • 从Map&lt;String,Object&gt; 构建 MoneyValue(或一些静态构建器)的构造函数怎么样?
  • 请分享MoneyValue类的代码
  • 为什么不为所有输入数据创建一个类,例如DetailsData?在这种情况下,您将能够创建自己的 JsonDeserializer&lt;DetailsData&gt; 并根据需要解析输入数据
  • 已更新。我有一个 EventDetails 类,如果添加新的详细信息,应该更改它。

标签: java json spring parsing


【解决方案1】:

如果一组属性(我的意思是输入数据的结构)是不可修改的,我们可以将其表示为 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 进入一些实用程序类。 综上所述,您可以通过以下方式更改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());
        }
    }
}

【讨论】:

  • 不幸的是,JSON 结构可以通过某种方式更改,即可以添加新字段。这就是为什么我试图找出一些简单的可编辑解决方案
  • 其实就够了。通过将映射器配置为忽略未知字段,我们将只需要在我们的类中。真的。感谢您指出我的错误。不知道为什么我试图让事情变得更复杂:D
  • 很高兴能帮到你!如果目标是获取货币列表,那就足够了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多