如果我要得到我的一个实体的I databaseentry得到正确的结果,但这个结果有换行符,这我不想有。我想是这样的(一个jsonfile):
{
"id" : 20706,
"name" : "Ecole des Ponts ParisTech",
"institution_type" : {
"id" : 2,
"name" : "Research facility"
},
但我得到的是:
{"institution":["{\r\n \"id\" : 20706,\r\n \"name\" : \"Ecole des Ponts ParisTech\",\r\n \"institution_type\" : {\r\n \"id\" : 2,\r\n \"name\" : \"Research facility\"\r\n },
我的代码来获得这样的:
ObjectMapper objectMapper = ObjectMapperFactory.getObjectMapper();
EditorialDAO dao = EditorialManager.dao();
String valueValue = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(dao.get(Institution.class,20706));
是的,我希望有一个字符串,但不能与换行符和\我的“。
如跟着我ObjectMapper声明:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.disable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.configure(SerializationFeature.EAGER_SERIALIZER_FETCH, true);
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
编辑:让valueValue后,下面的代码:
String response = objectMapper.writeValueAsString(dao.get(Basic.class, 323));
JSONObject jsonObject = new JSONObject(response);
jsonObject.put(institution, valueValue);
response = jsonObject.toString();
dao.merge(objectMapper.readValue(response, Basic.class));
如果我尝试合并我得到这个错误:
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of Institution: no String-argument constructor/factory method to deserialize from String value();
我不明白:我只是把那inpout从数据库正好到我的JSON和我Basic.class实体的机构类型。
@Entity
@JsonInclude(Include.NON_EMPTY)
public class Basis implements{
@Id
@SortableField
@SequenceGenerator(name = "basis_generator", sequenceName = "basis_id_basis_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "basis_generator")
@Column(name="id_basis")
@JsonView(View.Minimal.class)
private int id;
@ManyToOne
@NotFound(action=NotFoundAction.IGNORE)
@JsonView(View.Minimal.class)
@JoinColumn(name="id_institution")
private Institution institution;
这个问题的解决方案是不是通过valueValue
直接到你jsonObject
。相反,它需要一个JsonObject
它自己的。
JSONObject jsonObject = new JSONObject(response);
jsonObject.put(institution, new JSONObject(valueValue));
直接传递JSON值导致下面的输出,其中包括引号被转义,并且额外的引号已遍布增值。这种方式只能用于基本类型。
{"institution":"{\"id\":20706,\"name\":\"Ecole des Ponts ParisTech\",\"institutionType\":{\"id\":2,\"name\":\"Research facility\"}}","id":1}
如果包裹成一个新的JsonObject
,结果是正确的AA表现,这jackson
可以处理。
{"institution":{"name":"Ecole des Ponts ParisTech","institutionType":{"name":"Research facility","id":2},"id":20706},"id":1}
PS:无论是原始的字符串是在漂亮的打印格式与否并不重要。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句