简体   繁体   English

将JSON映射到简单的Java子类

[英]Mapping JSON to simple Java subclass

I'm trying to move from default Json API in Android to GSON (or Jackson). 我正在尝试从Android中的默认Json API迁移到GSON(或Jackson)。 But I'm stuck at trying to convert JSONObject to Java object. 但是我一直试图将JSONObject转换为Java对象。 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: 我试图映射到Dog class的JSON是这样的:

{
   "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. Name已正确映射,但id尚未映射。

How can I achieve this with GSON (or Jackson) libraries, if it's simpler? 如果更简单,如何使用GSON(或Jackson)库实现呢?

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. 希望它也对您有用。

Your code should work fine. 您的代码应该可以正常工作。 Try checking what jsonObject.toString() returns. 尝试检查jsonObject.toString()返回什么。 Whether that matches the actual json or not. 是否与实际json匹配。 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]"
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM