json转对象和对象数组localdatetime出错解决

json转对象

创建一个配置文件LocalDateTimeConfig类
下面展示一些 内联代码片


package com.ryan.cofig;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
 

@Configuration
public class LocalDateTimeConfig {
    private final static String DATE_TIME_FORMATTER = "yyyy-MM-dd HH:mm:ss";
    @Bean
    ObjectMapper objectMapper() {
        return new Jackson2ObjectMapperBuilder()
                .findModulesViaServiceLoader(true)
                .serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(
                        DateTimeFormatter.ofPattern(DATE_TIME_FORMATTER)))
                .deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(
                        DateTimeFormatter.ofPattern(DATE_TIME_FORMATTER)))
                .build();
    }
    }

```javascript
// 测试部分

    @Autowired
    private ObjectMapper objectMapper;
 
    @Test
    public void test() throws IOException {
        UserTest userTest = new UserTest("mocar", LocalDateTime.now(), 
LocalDateTime.of(2020, 5, 1, 12, 0));
        System.out.println(userTest);
        System.out.println("------将对象转json,如下-----------");
        String json = objectMapper.writeValueAsString(userTest);
        System.out.println(json);
        System.out.println("------将json转对象,如下-----------");
        UserTest userTest1 = objectMapper.readValue(json, UserTest.class);
        System.out.println(userTest1);

json转对象数组

  ObjectMapper mapper = new ObjectMapper();
        List<MltWaitLendReco> lendReco = mapper.readValue(listStr,new TypeReference<List<MltWaitLendReco>>() { });
        System.out.println(lendReco.get(0).getId());

你可能感兴趣的:(json转对象和对象数组localdatetime出错解决)