JDA icon indicating copy to clipboard operation
JDA copied to clipboard

Add DataPath util

Open MinnDevelopment opened this issue 2 years ago • 0 comments

Pull Request Etiquette

Changes

  • [ ] Internal code
  • [x] Library interface (affecting end-user code)
  • [ ] Documentation
  • [ ] Other: _____

Closes Issue: NaN

Description

This new util class allows to access deep nested fields with a simple path expression.

Example

long value = DataPath.getLong(object, "data.options[0].value");

This also allows safe-calls similar to kotlin via ?. delimiters:

long value = DataPath.getLong(object, "data?.options?[0]?.value?", 0L);

This would be equivalent to:

long value = 0L;
DataObject data = object.optObject("data").orElse(null);
if (data != null)
{
  DataArray options = data.optArray("options").orElse(null);
  if (options != null)
    value = options.getLong("value", 0L);
}

I'm sure you can see the appeal.

Motivation

This is very useful in various places, and now also relevant in the case of Event#getRawData which usually only is used to access a specific part of the json payload. Previously, you would have to exhaustively get each object and array down the path, which is especially annoying with optionals.

TODO

  • [x] Array equivalent methods for each type
  • [x] Documentation for all the new getters, including examples
  • [x] Unit tests

MinnDevelopment avatar Aug 10 '22 14:08 MinnDevelopment