Reputation: 291
I'm trying to move from default Json API in Android to GSON (or Jackson). But I'm stuck at trying to convert JSONObject to Java object. I've read many tutorials, but found nothing helpful.
I have these two classes (these are just for simplicity):
public class Animal {
@SerializedName("id")
private int id;
//getters and setters
}
public class Dog extends Animal{
@SerializedName("Name")
private String name;
//getters and setters
}
The JSON that I'm trying to map to Dog class
is this:
{
"id" : "1",
"Name" : "Fluffy"
}
I'm using this code:
Gson gson = new Gson();
Dog dog = gson.fromJson(jsonObject.toString(), Dog.class);
Name
is being mapped ok, but id
is not.
How can I achieve this with GSON (or Jackson) libraries, if it's simpler?
Upvotes: 0
Views: 2949
Reputation: 8499
Your code should work fine. Try checking what jsonObject.toString()
returns. Whether that matches the actual json or not. Example
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
class Animal {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Animal [id=" + id + "]";
}
}
class Dog extends Animal{
@SerializedName("Name")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Dog [name=" + name + ", Id=" + getId() + "]";
}
}
public class GSonParser {
public static void main(String[] args) throws Exception {
String json = "{\"id\" : \"1\", \"Name\" : \"Fluffy\"}";
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(json);
Gson gson = new Gson();
Dog dog = gson.fromJson(jsonObject.toString(), Dog.class);
System.out.println(dog); // Prints "Dog [name=Fluffy, Id=1]"
}
}
Upvotes: 1
Reputation: 3054
For Jackson I use this code
private static ObjectMapper configMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY)
.withGetterVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY)
.withSetterVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY)
.withCreatorVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY));
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}
private Dog readDog(String json) {
Dog ret = null;
if (json != null) {
ObjectMapper mapper = configMapper();
try {
ret = mapper.readValue(json, Dog.class);
} catch (Exception e) {
Log.e("tag", Log.getStackTraceString(e));
return null;
}
}
return ret;
}
Hope it works for you as well.
Upvotes: 1