将json对象转换为entity / joda日期

时间:2014-03-15 09:22:14

标签: java json spring spring-mvc jackson

我有权利:

@Entity
@Table
   public class product implements Serializable{

private static final long serialVersionUID = 7166167496114624228L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@NotEmpty
@Size(max=300)
private String name;
private String description;
@Size(max=200)
private String text_small;
@Size(max=200)
@NotEmpty
private String url;
@Column
@Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
private DateTime dateStart = new DateTime();
@Column
@Type(type = "org.joda.time.contrib.hibernate.PersistentDateTime")
private DateTime dateEnd = null;
private boolean delete =    false;
private boolean status              =   false;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "shop_id")
@Cascade({CascadeType.ALL})
private Shop shop;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "id_type")
@Cascade({CascadeType.ALL})
private TypProduct typProduct;

@ManyToMany(mappedBy="category", fetch=FetchType.LAZY)
private Set<CategoryProduct> category = new HashSet<CategoryProduct>();
 ...settert and getters

我的控制器接收数据:

@RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Map<String, Object> saveAjax(
        @Valid @RequestBody Product product, BindingResult result) {
    ......
    }

我想通过ajax / json编辑这个实体,我使用jackson 我有关于转换dateStart,dateEnd,shop,typProduct和category的问题。 @InitBinder中的Standart CustomEditor不适用于此。 如何使用MappingJacksonHttpMessageConverter,任何人都有一个示例解决方案?

THX。

2 个答案:

答案 0 :(得分:0)

我有例子......

我的ajax使用jquery

function postIt(){
            $.ajax({
              url: "${pageContext.request.contextPath}/test",             
              data:JSON.stringify({id:1, name:"a normal json object face"}),
              type: 'POST', 
              dataType: 'json', 
              contentType: 'application/json',
              mimeType: 'application/json'
            }).done(function() {
              $( this ).addClass( "done" );
            });
        }

我的控制器

@RequestMapping(value="/test", method = RequestMethod.POST, consumes="application/json")
public @ResponseBody String test(@RequestBody final String face){
    System.out.println(face);
    return new Gson().toJson(face);
}

jackson依赖项已下载到我的lib。

答案 1 :(得分:0)

感谢您的回复,我自己解决了问题,如果有人需要解决方案

我在我的模型中添加set方法:

 @JsonDeserialize(using = DeserializerJodaDateTime.class)

和DeserializerJodaDateTime.class看起来像:

public class DeserializerJodaDateTime extends JsonDeserializer<DateTime> {

@Override
public DateTime deserialize(JsonParser json, DeserializationContext arg1)
        throws IOException, JsonProcessingException {
      DateTimeFormatter formatDaty = DateTimeFormat.forPattern("dd/MM/yyyy");
    if (json.getText().isEmpty())
        return null;
    return formatDaty.parseDateTime(json.getText());
}

 }

如果我想使用service / dao来获得反序列化实体(关系示例)

public class DeserializeShop extends JsonDeserializer<Shop> {

@Autowired
ShopService shopService;

public DeserializerShop() {
    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}

@Override
public Shop deserialize(JsonParser json, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    return shopService.getShop(Integer.parseInt(json
            .getText()));
}

}