使用 Gson 反序列化 Map<String、Object> 字段

2022-09-03 02:48:05

我有一个具有此结构的User对象:

class User {
    private String id;
    private String name;
    private Map<String, Object> properties;

    // GETTERS & SETTERS
}

我有一个具有此结构的JSON字符串:

{
    "user": {
        "id:"123456789",
        "name:"azerty",
        "emailHash":"123456789", // not used in User class
        "properties": {
            "p1":1,
            "p2":"test",
            "p3":[1, 2, 3, 4],
            "p4":{
               etc...
            }
        }
    }
}

属性的键是字符串,属性的值可以是字符串,int,数组,布尔值,映射等。

我尝试用Gson反序列化这个JSON字符串,如下所示:

JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonString);
JsonObject object = element.getAsJsonObject();

GsonBuilder builder = new GsonBuilder();
builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
Gson gson = builder.create();
User user = (User) gson.fromJson(object.get("user"), new TypeToken<User>() {}.getType());

字段“id”和“name”已正确注入,但字段“属性”保持为空。

你知道我做错了什么吗?提前感谢您的帮助!


答案 1

对我来说,这个代码:

public class Main {
    public static void main(String[] args) throws IOException {
    GsonBuilder builder = new GsonBuilder();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    Gson gson = builder.create();
    FileInputStream inputStream = new FileInputStream(new File("bobi.json"));
    InputStreamReader reader = new InputStreamReader(inputStream);
    User user = gson.fromJson(reader, User.class);
    System.out.println(user.getName());
    System.out.println(user.getId());
    for (String property : user.getProperties().keySet()) {
        System.out.println("Key: " + property + " value: " + user.getProperties().get(property));
    }
    reader.close();
}

打印此:

azerty
123456789
Key: p1 value: 1.0
Key: p2 value: test
Key: p3 value: [1.0, 2.0, 3.0, 4.0]
Key: p4 value: {}

但是,请记住,我已经在我解析的文件中剥离了包装json对象。该文件是:

{
        "id":"123456789",
        "name" : "azerty",
        "emailHash":"123456789", 
        "properties": {
            "p1":1,
            "p2":"test",
            "p3":[1, 2, 3, 4],
            "p4":{

            }
        }
}

此外,我还为 和 添加了右双引号,这在示例中没有。nameid

OP 请求的类。出于打印的原因,我添加了 getter 和 setters:User

import java.util.Map;

class User {
    private String id;
    private String name;
    private Map<String, Object> properties;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Map<String, Object> getProperties() {
        return properties;
    }
    public void setProperties(Map<String, Object> properties) {
        this.properties = properties;
    }
}

答案 2