草庐IT

java - JSON 解析错误 : Already had POJO for id

coder 2024-04-01 原文

我已经看到了一些关于这个主题的问题,但我无法将其应用到我的案例中,因为我尝试应用它们,但错误仍然存​​在。 所以我来揭露我的情况。

我读了一些关于它的评论,并说如果我在 Entidade 类中更改我的列 idEntidade 的名称,我就可以成功。但是我不能改变数据库。

我试图将 scope= Distritos.class 放入我的 @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "idDistrito") 但它不起作用.

我需要帮助。

我正在尝试使用带有 Angular 的 spring MVC 将数据保存在我的数据库中。当我点击保存数据时,我得到了这个错误

2017-09-29 13:28:02.126  WARN 2716 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Already had POJO for id (java.lang.Long) [[ObjectId: key=1, type=com.fasterxml.jackson.databind.deser.impl.PropertyBasedObjectIdGenerator, scope=java.lang.Object]]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Already had POJO for id (java.lang.Long) [[ObjectId: key=1, type=com.fasterxml.jackson.databind.deser.impl.PropertyBasedObjectIdGenerator, scope=java.lang.Object]] (through reference chain: digifred.global.model.Distritos["idEntidade"]->digifred.global.model.Entidades["idEntidade"])
2017-09-29 13:28:02.126  WARN 2716 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Already had POJO for id (java.lang.Long) [[ObjectId: key=1, type=com.fasterxml.jackson.databind.deser.impl.PropertyBasedObjectIdGenerator, scope=java.lang.Object]]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Already had POJO for id (java.lang.Long) [[ObjectId: key=1, type=com.fasterxml.jackson.databind.deser.impl.PropertyBasedObjectIdGenerator, scope=java.lang.Object]] (through reference chain: digifred.global.model.Distritos["idEntidade"]->digifred.global.model.Entidades["idEntidade"])
2017-09-29 13:46:14.096  INFO 2716 --- [      Thread-46] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@53b2ae5: startup date [Fri Sep 29 13:23:36 BRT 2017]; root of context hierarchy

我有这些课

@Entity
@Table(name = "distritos", schema="glb")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Distritos.findAll", query = "SELECT d FROM Distritos d"),
    @NamedQuery(name = "Distritos.findByIdDistrito", query = "SELECT d FROM Distritos d WHERE d.idDistrito = :idDistrito"),
    @NamedQuery(name = "Distritos.findByNome", query = "SELECT d FROM Distritos d WHERE d.nome = :nome"),
    @NamedQuery(name = "Distritos.findByCodigoDne", query = "SELECT d FROM Distritos d WHERE d.codigoDne = :codigoDne"),
    @NamedQuery(name = "Distritos.findByFlagAtivo", query = "SELECT d FROM Distritos d WHERE d.flagAtivo = :flagAtivo")})




@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "idDistrito")        
public class Distritos implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id_distrito")
    private Long idDistrito;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 70)
    @Column(name = "nome")
    private String nome;
    @Size(max = 8)
    @Column(name = "codigo_dne")
    private String codigoDne;
    @Column(name = "flag_ativo")
    private Integer flagAtivo;
    @JoinColumn()
    @ManyToOne
    private Entidades idEntidade;
    @JoinColumn()
    @ManyToOne(optional = false)
    private Municipios idMunicipio;
    @JoinColumn()
    @ManyToOne(optional = false)
    private Ufs idUf;

  gets and sets .. 
}

类(Class)斗争

@Entity
@Table(name = "entidades", schema="glb")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Entidades.findAll", query = "SELECT e FROM Entidades e"),
    @NamedQuery(name = "Entidades.findByIdEntidade", query = "SELECT e FROM Entidades e WHERE e.idEntidade = :idEntidade"),
    @NamedQuery(name = "Entidades.findByBairro", query = "SELECT e FROM Entidades e WHERE e.bairro = :bairro"),
    @NamedQuery(name = "Entidades.findByBrasao", query = "SELECT e FROM Entidades e WHERE e.brasao = :brasao"),
    @NamedQuery(name = "Entidades.findByCnpj", query = "SELECT e FROM Entidades e WHERE e.cnpj = :cnpj"),
    @NamedQuery(name = "Entidades.findByComplemento", query = "SELECT e FROM Entidades e WHERE e.complemento = :complemento"),
    @NamedQuery(name = "Entidades.findByEmail", query = "SELECT e FROM Entidades e WHERE e.email = :email"),
    @NamedQuery(name = "Entidades.findByLogradouro", query = "SELECT e FROM Entidades e WHERE e.logradouro = :logradouro"),
    @NamedQuery(name = "Entidades.findByNome", query = "SELECT e FROM Entidades e WHERE e.nome = :nome"),
    @NamedQuery(name = "Entidades.findByNumero", query = "SELECT e FROM Entidades e WHERE e.numero = :numero"),
    @NamedQuery(name = "Entidades.findBySigla", query = "SELECT e FROM Entidades e WHERE e.sigla = :sigla"),
    @NamedQuery(name = "Entidades.findByTelefone", query = "SELECT e FROM Entidades e WHERE e.telefone = :telefone")})


@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "idEntidade")  
public class Entidades implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    private Long idEntidade;
    @Size(max = 50)
    private String bairro;
    private BigInteger brasao;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 14)
    private String cnpj;
    @Size(max = 20)
    private String complemento;
    // @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="E-mail inválido")//if the field contains email address consider using this annotation to enforce field validation
    @Size(max = 30)
    private String email;
    @Size(max = 50)
    private String logradouro;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 70)
    private String nome;
    @Size(max = 20)
    private String numero;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 4)
    private String sigla;
    @Size(max = 12)
    private String telefone;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idEntidade")
    private Collection<EntidadesAdministradores> entidadesAdministradoresCollection;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "entidades")
    private Collection<Bairros> bairrosCollection;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idEntidade")
    private Collection<PessoasDeficiencias> pessoasDeficienciasCollection;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idEntidade")
    private Collection<PessoasEnderecos> pessoasEnderecosCollection;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idEntidade")
    private Collection<EntidadesLicencas> entidadesLicencasCollection;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idEntidade")
    private Collection<PessoasContatos> pessoasContatosCollection;
    @OneToMany(mappedBy = "idEntidade")
    private Collection<Logradouros> logradourosCollection;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idEntidade")
    private Collection<Pessoas> pessoasCollection;
    @JoinColumn()
    @ManyToOne(optional = false)
    private Municipios idMunicipio;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "idEntidade")
    private Collection<PessoasCaracteristicas> pessoasCaracteristicasCollection;

    public Entidades() {
    }
          .... gets and sets . . 

    }

类 DistritosController

@RestController
@RequestMapping(value="/user")
public class DistritosController {

    @Autowired
    DistritosService distritosService; 


    @RequestMapping(method = RequestMethod.POST, value = "/distritos", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Distritos> cadastrarDistritos(@RequestBody Distritos distritos) {
        Distritos distritosCadastrado = distritosService.cadastrar(distritos);
        return new ResponseEntity<Distritos>(distritosCadastrado, HttpStatus.CREATED);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/distritos", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Collection<Distritos>> buscarTodosDistritos() {
        Collection<Distritos> distritosBuscados = distritosService.buscarTodos();
        return new ResponseEntity<>(distritosBuscados, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.GET, value = "/distritos/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Distritos> buscarDistritosPorId(@PathVariable int id) {
        Distritos distritos = distritosService.buscaPorId(id);
        return new ResponseEntity<>(distritos, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.DELETE, value = "/distritos/{id}")
    public ResponseEntity<Distritos> excluirDistritos(@PathVariable int id) {
        Distritos distritoEncontrado = distritosService.buscaPorId(id);
        if (distritoEncontrado == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        distritosService.excluir(distritoEncontrado);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.PUT, value = "/distritos", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Distritos> alterarDistritos(@RequestBody Distritos distritos) {
        Distritos distritoAlterado = distritosService.alterar(distritos);
        return new ResponseEntity<Distritos>(distritoAlterado, HttpStatus.OK);
    }


}

最佳答案

有两个问题:

1。身份范围

两者都是 @JsonIdentityInfo 的应该是范围内的,因为你的两个类都有相同的生成器类型 - ObjectIdGenerators.PropertyGenerator.class .

Scope is used to define applicability of an Object Id: all ids must be unique within their scope; where scope is defined as combination of this value and generator type. Comparison is simple equivalence, meaning that both type generator type and scope class must be the same. Scope is used for determining how many generators are needed; more than one scope is typically only needed if external Object Ids have overlapping value domains (i.e. are only unique within some limited scope)

对于 Distritos :

@JsonIdentityInfo(scope = Distritos.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "idDistrito")

对于 Entidades :

@JsonIdentityInfo(scope = Entidades.class, generator = ObjectIdGenerators.PropertyGenerator.class, property = "idEntidade")

2。字段命名

@JoinColumn()
@ManyToOne
private Entidades idEntidade;

以某种方式干扰

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
private Long idEntidade;

当您将完整的 Distritos 传递给 Jackson 反序列化器时对象(包含 Entidades 内部,如您的示例所示)。

我做了一些调试,发现 BeanDeserializer (按名称解析字段)无法反序列化属性字段,因为它与 id 字段同名,所以我更改了 idEntidadeentidadeDistritos类。

在这些更改之后,我的示例项目工作正常(因为我已经从您的类中删除了一些字段 - Distritos.idMunicipioDistritos.idUf 以及来自 Entidades 的所有 Collection)。您必须检查其他类(例如 MunicipiosUfs )是否有相同的问题,并修复它们。

关于java - JSON 解析错误 : Already had POJO for id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46493841/

有关java - JSON 解析错误 : Already had POJO for id的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  3. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  4. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  5. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  6. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  7. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  8. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  9. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  10. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

随机推荐