org.codehaus.jackson.map.JsonMappingException:无法从JSON字符串实例化类型[simple type,class models.Job]的值

时间:2012-06-20 20:08:37

标签: json rest playframework jackson

我使用playframework并尝试将一些json反序列化为java对象。 它工作得很好,在模型中解除了关系。我得到了以下异常

  

输入代码hereorg.codehaus.jackson.map.JsonMappingException:不能   从JSON实例化[simple type,class models.Job]类型的值   串;没有单字符串构造函数/工厂方法(通过引用   chain:models.Docfile [“job”])

我认为杰克逊与戏剧相结合可以做到这一点:

这是json

{"name":"asd","filepath":"blob","contenttype":"image/png","description":"asd","job":"1"}

这是我的代码,没什么特别的:

public static Result getdata(String dataname) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            Docfile docfile = mapper.readValue((dataname), Docfile.class);
            System.out.println(docfile.name);
            docfile.save();

        } catch (JsonGenerationException e) {

            e.printStackTrace();

        } catch (JsonMappingException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return ok();
    }

希望对我有所帮助,谢谢 马库斯

更新:

Docfile Bean:

package models;

import java.util.*;

import play.db.jpa.*;
import java.lang.Object.*;
import play.data.format.*;
import play.db.ebean.*;
import play.db.ebean.Model.Finder;
import play.data.validation.Constraints.*;
import play.data.validation.Constraints.Validator.*;

import javax.persistence.*;

import com.avaje.ebean.Page;

@Entity
public class Docfile extends Model {

    @Id
    public Long id;

    @Required
    public String name;

    @Required
    public String description;

    public String filepath;

    public String contenttype;

    @ManyToOne
    public Job job;

    public static Finder<Long,Docfile> find = new Model.Finder(
            Long.class, Docfile.class
            );




    public static List<Docfile> findbyJob(Long job) {
        return find.where()
                .eq("job.id", job)
                .findList();
    }

    public static Docfile create (Docfile docfile, Long jobid) {
        System.out.println(docfile);
        docfile.job = Job.find.ref(jobid);
        docfile.save();
        return docfile;
    }
}

2 个答案:

答案 0 :(得分:5)

您可以更改JSON以描述您的“工作”实体:

{
   "name":"asd",
   "filepath":"blob",
   "contenttype":"image/png",
   "description":"asd",
   "job":{
      "id":"1",
       "foo", "bar"
   }
}

或者在Job bean中创建一个带有String参数的构造函数:

public Job(String id) {
// populate your job with its id
}

答案 1 :(得分:1)

限时+ ee:+ jax-rs&amp;&amp; +持久性,+ 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;
    ...
}