2011-09-13 41 views
0

我使用Spring Roo生成了一组休眠类和FlexJSON类。FlexJson反序列化对象引用

我有实体叫位置和实体叫评论。 位置有很多评论(1:M)。

我想生成JSON对象,它会在反序列化并插入引用现有的Location对象。

当我省略位置字段,一切工作正常,例如:

{ 
    "date": 1315918228639, 
    "comment": "Bosnia is very nice country" 
} 

我不知道如何引用位置字段。 我试过以下,但收效甚微:

{ 
    "location": 10, 
    "date": 1315918228639, 
    "comment": "Bosnia is very nice country" 
} 

其中位置编号为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; 

} 

回答

1

我已通过添加瞬态性能解决了问题。

@Transient 
public long getLocationId(){ 
    if(location!=null) 
     return location.getId(); 
    else 
     return -1; 
} 

@Transient 
public void setLocationId(long id){ 
    location = Location.findLocation(id); 
} 
+0

kthnx埃米尔法拉TI –

0

得到了类似的问题,但我不能改变传入的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()));我加了

0

我得到了同样的问题,并通过引入自定义对象工厂来解决它。由于JSONDeserializer期望位置属性(例如:“位置”:{“id”:10,..})的json对象,提供位置id作为字符串/整数(例如:“位置”:“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);