【问题标题】:Convert json object to entity/joda date将 json 对象转换为实体/joda 日期
【发布时间】:2014-03-15 09:22:13
【问题描述】:

我有实体:

@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 和类别有疑问。 @InitBinder 中的标准自定义编辑器不适用于此。 如何使用 MappingJacksonHttpMessageConverter,有人有示例解决方案吗?

谢谢。

【问题讨论】:

  • 执行代码时能否显示一些异常信息?

标签: java json spring spring-mvc jackson


【解决方案1】:

我有例子……

我的 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 依赖项已下载到我的库中。

【讨论】:

  • 对不起,我误解了你的问题。不要认为这个例子完全回答了你的问题。
【解决方案2】:

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

我在我的模型中添加了 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()));
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 2016-02-02
    • 2011-09-09
    相关资源
    最近更新 更多