org.codehaus.jackson.map.JsonMappingException:不能从J

2019-06-25 15:35发布

我用的是playframework并试图反序列化JSON一些到Java对象。 它工作得很好,exept模型之间的关系。 我得到了以下异常

输入代码hereorg.codehaus.jackson.map.JsonMappingException:无法实例类型的值[简单类型,类models.Job]从JSON字符串; 无单String构造/工厂方法(通过引用链:models.Docfile [“工作”])

我认为杰克逊与游戏能做到这一点的组合:

这是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豆:

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;
    }
}

Answer 1:

你要么改变JSON为了描述你的“工作”实体:

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

或者你创建你的工作豆字符串参数的构造函数:

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


Answer 2:

当有限的时间+ EE:+ JAX-RS && +持久性,+ 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;
    ...
}


文章来源: org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class models.Job] from JSON String