Created
March 20, 2018 15:44
-
-
Save emanuelet/a32330c0b372028b5f115697d77ff58f to your computer and use it in GitHub Desktop.
Working JacksonXML Parser for Hawk 2+
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 android.text.TextUtils; | |
import com.fasterxml.jackson.core.JsonProcessingException; | |
import com.fasterxml.jackson.databind.JavaType; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.fasterxml.jackson.databind.ObjectReader; | |
import com.orhanobut.hawk.Parser; | |
import java.io.IOException; | |
import java.lang.reflect.Type; | |
public class JacksonParser implements Parser { | |
private final ObjectMapper mapper; | |
public JacksonParser() { | |
this.mapper = new ObjectMapper(); | |
} | |
@Override | |
public <T> T fromJson(String content, Type type) { | |
if (TextUtils.isEmpty(content)) { | |
return null; | |
} | |
JavaType javaType = mapper.getTypeFactory().constructType(type); | |
ObjectReader objectReader = mapper.readerFor(javaType); | |
try { | |
return objectReader.readValue(content); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
return null; | |
} | |
} | |
@Override | |
public String toJson(Object body) { | |
try { | |
return mapper.writeValueAsString(body); | |
} catch (JsonProcessingException e) { | |
e.printStackTrace(); | |
return ""; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment