FasterXML / FasterXML/jackson-modules-base

GuiceInjectableValues doesn't seem to work correctly

Đang mở
#179 2 bình luận 0 reaction 0 người được giao Xem trên GitHub
guice
Ngôn ngữ chính
Java
Star
180
Fork
80
Merge trung bình
3 giờ 26 phút
Pull request đã merge (30 ngày)
1

Mô tả

Looking at the code of GuiceInjectableValues, it seems unable to handle string values, which is what you get by default:

```java
@Override
public Object findInjectableValue(
Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance
)
{
return injector.getInstance((Key) valueId);
}
```

We try to deserialize an object of class A:
```
package org.example;

import com.fasterxml.jackson.annotation.*;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;

public class A
{
private final String name;

@Inject
@JsonCreator
A(@JacksonInject X x, @Assisted @JsonProperty("name") String name) {
this.name = name;
}

public String getName() {
return name;
}
}
```

But valueId, in findInjectableValue, takes the name of the class, which is a string and cannot be converted to a Key, and we get an ClassCastException.

We ended-up creating our own InjectableValues subclass to handle this correctly:
```java
package org.example;

import com.fasterxml.jackson.databind.*;
import com.google.inject.*;

public class WorkingGuiceInjectableValues extends InjectableValues
{
private final Injector injector;

public WorkingGuiceInjectableValues(Injector injector) {
this.injector = injector;
}

public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) {
try
{
return this.injector.getInstance(WorkingGuiceInjectableValues.class.getClassLoader().loadClass((String)valueId));
}
catch (ClassNotFoundException e)
{
throw new RuntimeException(e);
}
}
}
```

This is what the main of our small toy program looks like:
```java
package org.example;

import java.io.*;

import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.module.guice.*;
import com.google.inject.Guice;

public class Main
{
public static void main(String[] args) throws IOException
{
System.err.println("hello world");
var objectMapper = new ObjectMapper();
var injector = Guice.createInjector(new ObjectMapperModule(), new InjectionModule());
var aFactory = injector.getInstance(AFactory.class);
var a = aFactory.create("New instance of org.example.A !!!");
System.err.println("a name: " + a.getName());
var file = new File("a.json");
objectMapper.writer().writeValue(file, a);
var a2 = objectMapper.reader(new GuiceInjectableValues(injector)).readValue(file, A.class);
System.err.println("a2 name: " + a2.getName());
}
}
```

Version of guice: 5.1.0
Version of jackson-module-guice: 2.13.3

Hướng dẫn đóng góp

Chưa lập chỉ mục được hướng dẫn đóng góp cho kho mã nguồn này

Đánh giá

Issue này chưa được đánh giá.

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.