使用spring反序列化JSON:未解析的前向引用Jackson异常

af7jpaap  于 2022-11-23  发布在  Spring
关注(0)|答案(4)|浏览(169)

我使用Spring开发API Rest项目。我有一个服务“CreateMateriel”,它将JSON作为参数数据:

物料对象的JSON

{
  "agence": 1, 
  "code": "001",
  "type": "MyType"
}

“Materiel”与“Agence”有多对一的关系。我放置了一个@JsonIdentityInfo标记以使用Agence的ID而不是Agence的对象(在看到this topic之后)

@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "idAgence")
@JsonIdentityReference(alwaysAsId = true)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "agence")
private Agence agence;

但是当我在POST /materiels上发送JSON时,我遇到了这个异常:

2017-05-16 18:00:53.021  WARN 8080 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unresolved forward references for: 
 at [Source: java.io.PushbackInputStream@767dfd7a; line: 5, column: 1]Object id [1] (for fr.app.domain.Agence) at [Source: java.io.PushbackInputStream@767dfd7a; line: 2, column: 14].; nested exception is com.fasterxml.jackson.databind.deser.UnresolvedForwardReference: Unresolved forward references for: 
 at [Source: java.io.PushbackInputStream@767dfd7a; line: 5, column: 1]Object id [1] (for fr.app.domain.Agence) at [Source: java.io.PushbackInputStream@767dfd7a; line: 2, column: 14].

经过多次研究,我已经看到了在JsonIdentityInfo中使用ObjectIdResolver...但我认为这不是最好的解决方案。这就是为什么我请求您帮助检测问题的根源。谢谢

物料控制器.java

package fr.app.controllers;

import fr.app.domain.Materiel;
import fr.app.services.MaterielService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collection;

@RestController @RequestMapping(value = "/materiels")
public class MaterielController {
    @Resource
    private MaterielService materielService;

    @RequestMapping(method = RequestMethod.POST)
    public Materiel createMateriel(@RequestBody Materiel materiel) {
        return this.materielService.createMateriel(materiel);
    }

    @RequestMapping(method = RequestMethod.GET)
    public Collection<Materiel> getAllMateriels() {
        return this.materielService.getAllMateriels();
    }

    @RequestMapping(value = "/{code}", method = RequestMethod.GET)
    public Materiel getMaterielByCode(@PathVariable(value = "code") String code) {
        //find materiel by code
        return this.materielService.getMaterielByCode(code);

    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void deleteMateriel(@PathVariable(value = "id") Long id) {
        this.materielService.deleteMateriel(id);

    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public Materiel updateMateriel(@PathVariable(value = "id") Long id, @RequestBody
            Materiel materiel) {

            materiel.setIdMateriel(id);

        return this.materielService.updateMateriel(materiel);

    }
}

材料.java

package fr.app.domain;

import com.fasterxml.jackson.annotation.*;

import javax.persistence.*;

@Entity
public class Materiel {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long idMateriel;

    @Column(name = "type_materiel", nullable = false)
    private String type;

    @Column(name = "code_materiel", unique = true, nullable = false)
    private String code;

    @JsonIdentityInfo(
            generator = ObjectIdGenerators.PropertyGenerator.class,
            property = "idAgence")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "agence")
    private Agence agence;

    public Materiel() {    }

    public Materiel(String type, String code, String dateScan) {
        this.type = type;
        this.code = code;
        this.dateScan = dateScan;
    }

    public Long getIdMateriel() {
        return idMateriel;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Agence getAgence() {
        return agence;
    }

    public void setAgence(Agence agence) {
        if(this.agence != null)
            this.agence.deleteMateriel(this);
        this.agence = agence;
        this.agence.addMateriel(this);
    }
}

物料服务.java

package fr.app.services;

import fr.app.domain.Materiel;
import fr.app.repositories.MaterielRepository;
import org.apache.commons.collections.IteratorUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;

@Service(value = "materielService")
public class MaterielServiceImpl implements MaterielService {
    @Resource
    private MaterielRepository materielRepository;

    ...

    @Override
    public Materiel createMateriel(Materiel materiel) {
        return this.materielRepository.save(materiel);
    }

   ...
}

代理.java

package fr.app.domain;

import com.fasterxml.jackson.annotation.*;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

@Entity
public class Agence {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long idAgence;

    @Column(name = "nom",unique = true, nullable = false)
    private String nom;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "agence")
    private Set<Materiel> materiels = new HashSet<Materiel>();

    public Agence() { }

    public Agence(String nom) {
        this.nom = nom;
    }

    public Long getIdAgence() {
        return idAgence;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public Set<Materiel> getMateriels() {
        return materiels;
    }

    public void setMateriels(Set<Materiel> materiels) {
        this.materiels = materiels;
    }

    public void addMateriel(Materiel materiel) {
        this.materiels.add(materiel);
    }

    public void deleteMateriel(Materiel materiel) {
        this.materiels.remove(materiel);
    }

}

pom.xml文件

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <version>3.0</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.9.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.9.Final</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
        <scope>compile</scope>
    </dependency>

    <!-- Needed for JSON View -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.6</version>
    </dependency>
</dependencies>
agyaoht7

agyaoht71#

还好我发现了问题。
最后,我需要添加解析器。因此,我找到here一个实现ObjectIDResolver的示例:

import com.fasterxml.jackson.annotation.ObjectIdGenerator;
import com.fasterxml.jackson.annotation.ObjectIdResolver;

import javax.persistence.EntityManager;

/**
 * @author fta on 20.12.15.
 */

public class EntityIdResolver
        implements ObjectIdResolver {

    private EntityManager entityManager;

    public EntityIdResolver(
            final EntityManager entityManager) {

        this.entityManager = entityManager;

    }

    @Override
    public void bindItem(
            final ObjectIdGenerator.IdKey id,
            final Object pojo) {

    }

    @Override
    public Object resolveId(final ObjectIdGenerator.IdKey id) {

        return this.entityManager.find(id.scope, id.key);
    }

    @Override
    public ObjectIdResolver newForDeserialization(final Object context) {

        return this;
    }

    @Override
    public boolean canUseFor(final ObjectIdResolver resolverType) {

        return false;
    }

}

接下来我加入@JsonIdentityInfo

@Entity
@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "idAgence",
        resolver = EntityIdResolver.class,
        scope=Agence.class)
public class Agence {
    // ... 
}
juzqafwq

juzqafwq2#

由于一对多的关系,你似乎有一个循环的对象图。对于那些你可以使用JSOG serializer plugin for Jackson
它应该处理循环对象图的序列化和反序列化(从Jackson2.5.1开始)

@JsonIdentityInfo(generator=JSOGGenerator.class)
public class Person {
    String name;
    Person secretSanta;
}
du7egjpx

du7egjpx3#

您有两个域:Materiel和Agence。当Jackson试图反序列化Materiel时,它调用方法getAgence。此方法返回一个Agence对象,Jackson也将反序列化该对象。当Jackson调用方法getMeteriels(Agence的)时,它返回一个也将反序列化的Materiel集。问题是Jackson将再次尝试反序列化该集中的每个Materiel。同样的问题是here

um6iljoc

um6iljoc4#

对于最后一个异常(utf-8),您可以按如下所示更改控制器的签名:

@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Bean> create(HttpServletRequest  request) throws IOException {
    // getting the posted value
    String body = CharStreams.toString(request.getReader());
    Bean bean = new ObjectMapper().readValue(body, service.getBeanClass());
    bean.setId(null);
    Bean saved = service.save(bean);

    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(saved.getId()).toUri();
    return ResponseEntity.created(location).body(saved);
}

使用此解决方案,您可以完全控制Map。
尽情享受

相关问题