将JSON文档保留为String

时间:2015-08-21 08:02:17

标签: java json jpa spring-boot

我有一个接收JSON RequestBody的控制器,如下所示:

{  
   "status":"pending",
   "status1":"pending",
   "status2":"pending",
   "status3":"pending",
   "specs":{  
      "width":1000,
      "height":1507,
      ........some other fields, any number of fields..
   },
}

我有Entity

@Entity
public class MyBean implements Serializable {

    @Id
    @GeneratedValue
    Long id;

    public String status;
    public String status1;
    public String status2;
    public String status3;
}

和我的Controller类:

@RequestMapping(value = "/insert", method = RequestMethod.POST)
public void insert(@RequestBody MyBean myBean) {
    return myService.save(myBean);
}

我的问题是我想将specs(这是一个JSON文档)的值存储为Lob字段中的String,我不知道该怎么做。

1 个答案:

答案 0 :(得分:2)

将规格声明为public Map<String,Integer> specs; 并将Object转换为json使用Jackson fasterxml api,如下所示

MyBean bean=new MyBean();
    bean.setId(new Long(1));
    bean.setStatus("pending");
    bean.setStatus1("pending");
    bean.setStatus2("pending");
    bean.setStatus3("pending");

    Map<String, Integer> temp=new HashMap<String, Integer>();
    temp.put("width",1000);
    temp.put("height",1507);
    bean.setSpecs(temp);

    //Object to json
    StringWriter sw=new StringWriter();
    ObjectMapper mapper=new ObjectMapper();
    mapper.writeValue(sw,bean);
    System.out.println(sw.toString());


     //json to object
    MyBean newBean=mapper.readValue(sw.toString(), MyBean.class);
    System.out.println(newBean.toString());

如果你想在保存之前只序列化规格,那么使用相同的mapper.writeValue()函数将specs转换为json字符串 有关更多信息,请参阅this