Java 无法从 JSON 字符串实例化类型的值;没有单字符串构造函数/工厂方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23961000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can not instantiate value of type from JSON String; no single-String constructor/factory method
提问by Gustavo Bitencourt
I have following entities:
我有以下实体:
@Entity
@Table(name="APLICACAO")
public class Aplicacao implements Serializable, Entidade {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="CD_APLICACAO")
private Long codigo;
@Column(name="NM_APLICACAO")
@NotNull
private String nome;
@ManyToOne
@JoinColumn(name="CD_GRUPO")
private GrupoAplicacao grupoAplicacao;
....
}
And also:
并且:
@Entity
@Table(name = "GRUPO_APLICACAO")
public class GrupoAplicacao implements Serializable, Entidade {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "CD_GRUPO")
private Long codigo;
@Column(name = "NM_GRUPO")
@NotNull
private String nome;
@OneToMany(mappedBy = "grupoAplicacao",fetch=FetchType.EAGER)
private List<Aplicacao> listaAplicacao;
@OneToMany(mappedBy = "grupoAplicacao",fetch=FetchType.EAGER)
private List<GrupoAplicacaoUsuario> listaGrupoAplicacaoUsuario;
....
}
My HTML call controller "aplicacoesCreateController", like code bellow:
我的 HTML 调用控制器“aplicacoesCreateController”,如下代码:
<div class="col-xs-12" ng-controller="aplicacoesCreateController">
<form class="form-horizontal form-medium center" role="form" name="form" ng-submit="save()">
<div class="form-group">
<label for="nome" class="col-xs-4 control-label">Nome</label>
<div class="col-xs-8">
<input type="text" class="form-control input-sm" id="nome" placeholder="Nome" required ng-model="aplicacao.nome">
</div>
</div>
<div class="form-group">
<label for="nome" class="col-xs-4 control-label">Nome</label>
<div class="col-xs-8">
<select class="form-control" required ng-model="aplicacao.grupoAplicacao">
<option ng-repeat="grupo in grupos" value="{{ grupo }}">
{{ grupo.nome }}
</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-4 col-xs-8">
<button type="submit" class="btn btn-lg btn-size-md">Salvar</button>
</div>
</div>
</form>
</div>
And my Controller JavaScript:
还有我的控制器 JavaScript:
app.controller('aplicacoesCreateController', ['$scope','aplicacoesService','$location','reloadService','gruposService',
function ($scope,aplicacoesService,$location,reloadService,gruposService) {
$scope.grupos = gruposService.list();
$scope.save = function () {
aplicacoesService.create($scope.aplicacao);
reloadService.on('#/aplicacoes');
};
}]);
And Services JavaScript:
和服务 JavaScript:
app.factory('gruposService', ['$resource', function ($resource) {
return $resource('resources/grupo-aplicacao', {}, {
'list': { method: 'GET', isArray: true }
});
}]);
And other service:
和其他服务:
app.factory('aplicacoesService', ['$resource', function ($resource) {
return $resource('resources/aplicacao', {}, {
'list': { method: 'GET', isArray: true },
'create': { method: 'POST' }
});
}]);
When insert aplicacao entity, is show me the following error:
插入 aplicacao 实体时,显示以下错误:
Caused by: org.codehaus.Hymanson.map.JsonMappingException: Can not instantiate value of type [simple type, class br.com.techpeople.grape.entity.GrupoAplicacao] from JSON String; no single-String constructor/factory method (through reference chain: br.com.techpeople.grape.entity.Aplicacao["grupoAplicacao"])
Could you help me with this error?
你能帮我解决这个错误吗?
采纳答案by BoatCode
The error is telling you that you need a constructor method in your GrupoAplicacao class which accepts a string.
该错误告诉您,您的 GrupoAplicacao 类中需要一个接受字符串的构造函数方法。
@Entity
@Table(name = "GRUPO_APLICACAO")
public class GrupoAplicacao implements Serializable, Entidade {
....
GrupoAplicacao(String stringJSON){
setters;
}
}
回答by Gustavo Bitencourt
Thank you @BoatCode!
谢谢@BoatCode!
I did the following in my constructor:
我在构造函数中执行了以下操作:
public GrupoAplicacao(String grupoAplicacaoJSON) {
Gson gson = new Gson();
GrupoAplicacao grupoAplicacao = gson.fromJson(grupoAplicacaoJSON, GrupoAplicacao.class);
this.codigo = grupoAplicacao.getCodigo();
this.nome = grupoAplicacao.getNome();
this.listaAplicacao = grupoAplicacao.getListaAplicacao();
this.listaGrupoAplicacaoUsuario = grupoAplicacao.getListaGrupoAplicacaoUsuario();
}
Add the lib Gson and set the variables of GrupoAplicacao class.
添加 lib Gson 并设置 GrupoAplicacao 类的变量。
=)
=)
回答by Seba Cervantes
It seems that, from javascript, you are sending a string instead of an object. You can try by sending JSON.parse(stringGrupoAplicacao)
.
看来,从 javascript 中,您发送的是字符串而不是对象。您可以尝试通过发送JSON.parse(stringGrupoAplicacao)
.
That way, on the server side the object should be deserialized automatically with no needs of creating a special constructor.
这样,在服务器端,对象应该自动反序列化,而无需创建特殊的构造函数。
回答by Oleksii Kyslytsyn
Once the task and the same issue was in scope of: +limited time, +ee: +jax-rs && +persistence, +gson; I have solved it then as:
一旦任务和同一问题在以下范围内:+limited time, +ee: +jax-rs && +persistence, +gson; 我已经解决了它:
@Entity
@XmlRootElement
@Table(name="element")
public class Element implements Serializable {
public Element(String stringJSON){
Gson g = new Gson();
Element a = g.fromJson(stringJSON, this.getClass());
this.setId(a.getId());
this.setProperty(a.getProperty());
}
public Element() {}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
...
}
It's pretty close to Gustavo's Bitencourt solution, with maybe a bit different scope.
它非常接近 Gustavo 的 Bitencourt 解决方案,但范围可能略有不同。