Using Apache Commons Digester with JSON

520 views Asked by At

I am writing a class that extends a class that uses Digester to parse an XML response from an API (Example existing class, code snipper below). After receiving the response, the code creates an object and adds specific methods on that.

Code snippet edited for brevity:

      private Digester createDigester() {
        Digester digester = new Digester();

        digester.addObjectCreate("GeocodeResponse/result", GoogleGeocoderResult.class);
        digester.addObjectCreate("GeocodeResponse/result/address_component", GoogleAddressComponent.class);
        digester.addCallMethod("GeocodeResponse/result/address_component/long_name", "setLongName", 0);
...
        digester.addSetNext("GeocodeResponse/result/address_component", "addAddressComponent");

        Class<?>[] dType = {Double.class};
        digester.addCallMethod("GeocodeResponse/result/formatted_address", "setFormattedAddress", 0);
...
        digester.addSetNext("GeocodeResponse/result", "add");
        return digester;
      }
    }

The API that I will be calling, however, only supports JSON. I have found a probable solution, which involves converting the JSON to XML and then running it through Digester, but that seems incredibly hackish.

public JsonDigester(final String customRootElementName) {
    super(new JsonXMLReader(customRootElementName));
  }

Is there a better way to do this?

1

There are 1 answers

2
AudioBubble On

This class is specifically meant to deal with XML as per the documentation:

Basically, the Digester package lets you configure an XML -> Java object mapping module, which triggers certain actions called rules whenever a particular pattern of nested XML elements is recognized. A rich set of predefined rules is available for your use, or you can also create your own.

Why would you think it would work with JSON?