Created
June 20, 2013 13:49
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build(); | |
// XXX For JSON dates. Not applicable when using XML API | |
client.register(new XeroObjectMapperContextResolver()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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