我使用Spring,它生成了一组hibernate和FlexJSON类。
我有一个名为Location的实体和一个名为注释的实体。位置有许多注释(1:M)。
我正在尝试生成JSON对象,当反序列化并插入引用现有的Location对象时,JSON对象将产生JSON对象。
当我省略位置字段时,一切正常,例如:
{
"date": 1315918228639,
"comment": "Bosnia is very nice country"
}我不知道如何引用位置字段。我试过以下几点,但收效甚微:
{
"location": 10,
"date": 1315918228639,
"comment": "Bosnia is very nice country"
}位置id是10。
如何在JSON中引用位置字段?
编辑:添加评论实体:
@RooJavaBean
@RooToString
@RooJson
@RooEntity
public class Komentar {
private String comment;
@ManyToOne
private Location location;
@Temporal(TemporalType.TIMESTAMP)
@DateTimeFormat(style = "M-")
private Date date;
}发布于 2011-09-14 07:20:02
我通过增加瞬态属性来解决问题。
@Transient
public long getLocationId(){
if(location!=null)
return location.getId();
else
return -1;
}
@Transient
public void setLocationId(long id){
location = Location.findLocation(id);
}发布于 2012-10-14 16:19:24
遇到了类似的问题,但我无法更改传入的json消息,因此我更改了生成的方面文件:
@RequestMapping(value = "/jsonArray", method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> Komentar.createFromJsonArray(@RequestBody String json) {
for (Komentar komentar: Komentar.fromJsonArrayToProducts(json)) {
komentar.setLocation(Location.findLocation(komentar.getLocation().getId()));
komentar.persist();
}
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
return new ResponseEntity<String>(headers, HttpStatus.CREATED);
}komentar.setLocation(Location.findLocation(komentar.getLocation().getId()));是我加的。
发布于 2013-04-05 09:36:43
我也遇到了同样的问题,并通过引入自定义对象工厂来解决它。
由于JSONDeserializer期望位置属性(ex:" location ":{" id ":10,.})有一个json对象,所以将位置id作为字符串/整数(ex:" location ":"10")提供给您一个异常。
因此,我编写了LocationObjectFactory类,并告诉flexjson如何以我想要的方式反序列化Location类对象。
public class LocationObjectFactory implements ObjectFactory {
@Override
public Object instantiate(ObjectBinder context, Object value,
Type targetType, Class targetClass) {
if(value instanceof String){
return Location.findProblem(Long.parseLong((String)value));
}
if(value instanceof Integer){
return Location.findProblem(((Integer)value).longValue());
}
else {
throw context.cannotConvertValueToTargetType(value,targetClass);
}
}
}并反序列化json字符串,如下所示
new JSONDeserializer<Komentar>().use(null, Komentar.class).use(Location.class, new LocationObjectFactory()).deserialize(json);https://stackoverflow.com/questions/7402324
复制相似问题