将JSON映射到简单的Java子类

时间:2015-08-13 15:16:05

标签: java android json jackson gson

我试图从Android中的默认Json API迁移到GSON(或Jackson)。但是我一直试图将JSONObject转换为Java对象。我已经阅读了很多教程,但没有找到任何帮助。

我有这两个类(这些只是为了简单起见):

public class Animal {
    @SerializedName("id")
    private int id;

    //getters and setters
}

public class Dog extends Animal{
    @SerializedName("Name")
    private String name;

    //getters and setters
}

我尝试映射到Dog class的JSON是:

{
   "id" : "1",
   "Name" : "Fluffy"
}

我正在使用此代码:

Gson gson = new Gson();
Dog dog = gson.fromJson(jsonObject.toString(), Dog.class);

Name映射正常,但id不是。

如果GSON(或Jackson)库更简单,我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

对于杰克逊我使用此代码

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;
}

希望它也适合你。

答案 1 :(得分:1)

您的代码应该可以正常运行。尝试检查jsonObject.toString()返回的内容。是否匹配实际的json。实施例

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]"
    }

}