这是我的JSON数组: -
[
{
"firstName" : "abc",
"lastName" : "xyz"
},
{
"firstName" : "pqr",
"lastName" : "str"
}
]
Run Code Online (Sandbox Code Playgroud)
我在我的String对象中有这个.现在我想将它转换为Java对象并将其存储在Java对象的List中.例如在Student对象中.我使用下面的代码将其转换为Java对象列表: -
ObjectMapper mapper = new ObjectMapper();
StudentList studentList = mapper.readValue(jsonString, StudentList.class);
Run Code Online (Sandbox Code Playgroud)
我的列表类是: -
public class StudentList {
private List<Student> participantList = new ArrayList<Student>();
//getters and setters
}
Run Code Online (Sandbox Code Playgroud)
我的学生对象是: -
class Student {
String firstName;
String lastName;
//getters and setters
}
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么吗?我得到以下异常: -
Exception : com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of com.aa.Student out of START_ARRAY token
Run Code Online (Sandbox Code Playgroud) 可以使用私有字段和自定义参数构造函数反序列化为不使用注释而不使用Jackson修改类的类?
我知道在使用这种组合时杰克逊有可能:1)Java 8,2)用"-parameters"选项编译,3)参数名称与JSON匹配.但是在没有所有这些限制的情况下,默认情况下也可以在GSON中使用.
例如:
public class Person {
private final String firstName;
private final String lastName;
private final int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public static void main(String[] args) throws IOException {
String json = "{firstName: \"Foo\", lastName: \"Bar\", age: 30}";
System.out.println("GSON: " + deserializeGson(json)); // works fine
System.out.println("Jackson: " + deserializeJackson(json)); // error
}
public static Person deserializeJackson(String json) throws IOException {
ObjectMapper mapper = …
Run Code Online (Sandbox Code Playgroud) 我正在升级项目的版本,目前正在使用 jackson-databind-2.13.0 。但我注意到 ObjectMapper 的启用方法已被弃用。
他们说要像这样使用它。
@deprecated Since 2.13 use {@code JsonMapper.builder().enable(...)}
Run Code Online (Sandbox Code Playgroud)
但我无法使用它。
下面是我的 ObjectMapper 实例创建代码。我该如何改变?
@Bean(name = {"objectMapper"})
@Primary
ObjectMapper objectMapper() {
return newObjectMapper();
}
public static ObjectMapper newObjectMapper() {
ObjectMapper objectMapper =
new ObjectMapper()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(OffsetDateTime.class, new OffsetDateTimeSerializer());
javaTimeModule.addDeserializer(OffsetDateTime.class, new OffsetDateTimeDeserializer());
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
objectMapper
.registerModule(javaTimeModule)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
Run Code Online (Sandbox Code Playgroud)
}
解决方案:
ObjectMapper objectMapper = JsonMapper
.builder()
.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, …
Run Code Online (Sandbox Code Playgroud) 创建类的首选方法是什么?
最好,我会喜欢这样的工作:
@Data(onConstructor = @__(@JsonCreator))
Run Code Online (Sandbox Code Playgroud)
然后有所有领域private final
.但是,这甚至没有编译(我不知道为什么).运用
@AllArgsConstructor(onConstructor = @__(@JsonCreator))
Run Code Online (Sandbox Code Playgroud)
将编译,但只收益
InvalidDefinitionException: No serializer found for class
Run Code Online (Sandbox Code Playgroud) 更新后反序列化失败.
我从我的更新微服Spring 1.5.10.RELEASE
来Spring 2.0.3.RELEASE
,也更新了lombok
从1.16.14
到1.18.0
和jackson-datatype-jsr310
从2.9.4
到2.9.6
.
JSON字符串 -
{"heading":"Validation failed","detail":"field must not be null"}
Run Code Online (Sandbox Code Playgroud)
班级 -
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ErrorDetail {
private final String heading;
private final String detail;
private String type;
}
Run Code Online (Sandbox Code Playgroud)
方法调用 -
ErrorDetail errorDetail = asObject(jsonString, ErrorDetail.class);
Run Code Online (Sandbox Code Playgroud)
用于反序列化的方法 -
import com.fasterxml.jackson.databind.ObjectMapper;
// more imports and class defination.
private static <T> T asObject(final String str, Class<T> clazz) {
try { …
Run Code Online (Sandbox Code Playgroud) 我希望能够捕获我正在开发的spring-boot API中发生的一些jackson异常.例如,我有以下请求类,我想捕获当JSON请求对象中的"questionnaireResponse"键为空或空白时(即" "
在请求对象中)发生的错误.
@Validated
@JsonRootName("questionnaireResponse")
public class QuestionnaireResponse {
@JsonProperty("identifier")
@Valid
private Identifier identifier = null;
@JsonProperty("basedOn")
@Valid
private List<Identifier_WRAPPED> basedOn = null;
@JsonProperty("parent")
@Valid
private List<Identifier_WRAPPED> parent = null;
@JsonProperty("questionnaire")
@NotNull(message = "40000")
@Valid
private Identifier_WRAPPED questionnaire = null;
@JsonProperty("status")
@NotNull(message = "40000")
@NotEmptyString(message = "40005")
private String status = null;
@JsonProperty("subject")
@Valid
private Identifier_WRAPPED subject = null;
@JsonProperty("context")
@Valid
private Identifier_WRAPPED context = null;
@JsonProperty("authored")
@NotNull(message = "40000")
@NotEmptyString(message = "40005")
@Pattern(regexp = "\\d{4}-(?:0[1-9]|[1-2]\\d|3[0-1])-(?:0[1-9]|1[0-2])T(?:[0-1]\\d|2[0-3]):[0-5]\\d:[0-5]\\dZ", message = …
Run Code Online (Sandbox Code Playgroud) java exception-handling jackson spring-boot jackson-databind
在 Jackson 的早期版本中,我们在对象的序列化和反序列化期间使用以下两种方法来修改属性命名。
第一种方法:在类级别提及以下注释。
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
Run Code Online (Sandbox Code Playgroud)
第二种方法:在对象映射器本身中设置 PropertyNamingStrategy。
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCaseStrategy.class);
or,
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
Run Code Online (Sandbox Code Playgroud)
现在它已从 2.13 版本起被弃用。
https://github.com/FasterXML/jackson-databind/issues/2715
现在有什么替代方案可以替代上述事情。
谁能帮我解决这个问题吗?
正在尝试上述两种方式,但现在显示已弃用。
获取MismatchedInputException.在这里搜索了很多问题,但主要发现了JSONMappingException.我不明白他们是相同还是不同.
以下是实体:
@Entity
@Table
@NamedQueries({
@NamedQuery(name="User.findAll", query="SELECT u FROM User u"),
@NamedQuery(name="User.findByEmail", query="SELECT u FROM User u WHERE u.email=:pEmail")
})
public class User {
@Id
@GenericGenerator(name = "idGenerator", strategy = "uuid2")
@GeneratedValue(generator = "idGenerator")
private String id;
private String firstName;
private String lastName;
@Column(unique=true)
private String username;
@Column(unique=true)
private String email;
private String password;
private String role;
}
Run Code Online (Sandbox Code Playgroud)
所有的吸气剂和制定者都到位.
以下是控制器映射功能:
@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public User create(@RequestBody User user) {
return service.create(user);
}
Run Code Online (Sandbox Code Playgroud)
以下是服务:
@Override …
Run Code Online (Sandbox Code Playgroud) 由于外部原因,Map
我系统中的所有 java只能作为来自客户端的键值对列表接收,例如 aMap<String, Book>
实际上将作为 Json-serialized 接收List<MapEntry<String, Book>>
。这意味着我需要自定义我的 Json 反序列化过程以期望这种地图表示。
问题是JsonDeserializer
让我实施
deserialize(JsonParser p, DeserializationContext ctxt)
Run Code Online (Sandbox Code Playgroud)
无法访问检测到的应该反序列化的泛型类型的方法(Map<String, Book>
在上面的示例中)。如果没有这些信息,我将无法在List<MapEntry<String, Book>>
不失去类型安全性的情况下反序列化。
我正在查看Converter但它提供的上下文更少。
例如
public Map<K,V> convert(List<MapToListTypeAdapter.MapEntry<K,V>> list) {
Map<K,V> x = new HashMap<>();
list.forEach(entry -> x.put(entry.getKey(), entry.getValue()));
return x;
}
Run Code Online (Sandbox Code Playgroud)
但这可能会创建危险的映射,ClassCastException
在检索时会抛出异常,因为无法检查类型是否实际合理。有没有办法解决这个问题?
作为我期望的一个例子,GsonJsonDeserializer
看起来像这样:
T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
Run Code Online (Sandbox Code Playgroud)
即它以一种理智的方式提供对预期类型的访问。
使用Spring 1.5.8.RELEASE Jackson映射器给出以下异常。
Cannot deserialize value of type `java.util.Date` from String "2018-09-04T10:44:46": expected format "yyyy-MM-dd'T'HH:mm:ss.SSS"
Run Code Online (Sandbox Code Playgroud)
在[资料来源:未知;行:-1,列:-1](通过参考链:com.copart.conversationapi.calldisposition.model.vo.CallLogEntity [“ callEndTime”])
CallEntity.java
@JsonProperty("callEndTime")
@Column(name = "call_end_ts")
@JsonFormat(pattern="yyyy-MM-dd'T'HH:mm:ss.SSS")
private Date callEndTime;
Run Code Online (Sandbox Code Playgroud)
DAO.java
ObjectMapper mapper = new ObjectMapper();
HashMap<String, Object> finalHashMap;
finalHashMap = convertMultiToString(requestMap);
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
CallLogEntity callLogEntity = mapper.convertValue(finalHashMap, CallEntity.class);
Run Code Online (Sandbox Code Playgroud)
pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
Run Code Online (Sandbox Code Playgroud) jackson-databind ×10
java ×10
jackson ×8
spring-boot ×5
json ×4
lombok ×2
spring ×2
generics ×1
jackson2 ×1
objectmapper ×1
spring-mvc ×1