5

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

在此处输入代码org.codehaus.jackson.map.JsonMappingException:无法从JSON字符串实例化类型[简单类型,类models.Job]的值;没有单字符串构造函数/工厂方法(通过引用链:models.Docfile["job"])

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

这是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();
    }

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

更新:

文档文件豆:

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

2 回答 2

6

您可以更改 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
}
于 2012-06-21T13:53:01.510 回答
1

限时+ee: +jax-rs && +persistence, +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;
    ...
}
于 2016-01-24T21:04:09.350 回答