Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitrygusev/5822856 to your computer and use it in GitHub Desktop.
Save dmitrygusev/5822856 to your computer and use it in GitHub Desktop.
Example of calling Xero API using JSON format via Resteasy client with custom ObjectMapper
ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
// XXX For JSON dates. Not applicable when using XML API
client.register(new XeroObjectMapperContextResolver());
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.ext.ContextResolver;
import org.codehaus.jackson.map.ObjectMapper;
public class XeroObjectMapperContextResolver implements ContextResolver<ObjectMapper>
{
private final ObjectMapper xeroObjectMapper;
public XeroObjectMapperContextResolver()
{
xeroObjectMapper = new ObjectMapper();
DateFormat df = new DateFormat()
{
private static final long serialVersionUID = 1L;
private final Pattern PATTERN = Pattern.compile("/Date\\((\\d+)\\)/");
@Override
public StringBuffer format(Date date,
StringBuffer toAppendTo, FieldPosition fieldPosition)
{
throw new UnsupportedOperationException();
}
@Override
public Date parse(String source, ParsePosition pos)
{
Matcher matcher = PATTERN.matcher(source);
if (matcher.find())
{
String timeValue = matcher.group(1);
long time = Long.parseLong(timeValue);
pos.setIndex(source.length());
return new Date(time);
}
return null;
}
@Override
public Object clone()
{
// We're thread safe
return this;
}
};
// This will only work for responses, not for requests
xeroObjectMapper.setDeserializationConfig(
xeroObjectMapper.getDeserializationConfig().withDateFormat(df));
}
@Override
public ObjectMapper getContext(Class<?> objectType)
{
return xeroObjectMapper;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment