0

我正在尝试将页面中的字符串 id 转换为新的 ObjectID,因此我可以使用它 person.getId();

该页面发送一个字符串 id,但要填充,我必须将其转换为 ObjectID(否则它将打印“预期的对象但是字符串)

所以我创建了一个反序列化,在它进入 Person 对象之前拦截 jsonElement

@Override
    public ObjectId deserialize(JsonElement jsElement, Type Type,
            JsonDeserializationContext context) throws JsonParseException {

        //the id that i receive is this one -> 53c9e605278cd4d23e1152bb

        ObjectId obj = new ObjectId(jsElement.toString());
        return obj;
    }

这样我得到这个错误:

 java.lang.IllegalArgumentException: invalid ObjectId ["53c9e605278cd4d23e1152bb"]

但如果我以这种方式使用:

  @Override
        public ObjectId deserialize(JsonElement jsElement, Type Type,
                JsonDeserializationContext context) throws JsonParseException {

            //the id that i receive is this one -> 53c9e605278cd4d23e1152bb

            ObjectId obj = new ObjectId("53c9e605278cd4d23e1152bb");
            return obj;
        }

它工作,为什么?如果它直接从 JsonElement = 不工作,但如果我使用 ctrl c + ctrl v,它工作!

4

1 回答 1

0

无意间找到了答案

.toString() 添加引号,我需要使用 .getAsString

Java中的Gson、JsonElement、字符串比较

于 2014-07-21T01:20:43.757 回答