JsonConfig.java
Код: Выделить всё
@Configuration
@ComponentScan(basePackageClasses = {ru.vniiem.mcc.initstateservice.models.UserModel.class })
public class JsonConfig {
private static final Logger LOG = LogManager.getLogger(JsonConfig.class);
@Autowired
public UserModel[] usrModel;
@Bean
public void usersLog() {
LOG.info(usrModel);
}
}
Код: Выделить всё
@Component
@PropertySource(value = "classpath:users.json", factory = JsonPropertySourceFactory.class)
@ConfigurationProperties
public class UserModel {
@Value("${login}")
private String login;
@Value("${password}")
private String password;
public UserModel() {
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Код: Выделить всё
public class JsonPropertySourceFactory
implements PropertySourceFactory {
@Override
public PropertySource createPropertySource(
String name, EncodedResource resource)
throws IOException {
Map readValue = new ObjectMapper()
.readValue(resource.getInputStream(), Map.class);
return new MapPropertySource("json-property", readValue);
}
}
Код: Выделить всё
[
{
"login": "aaa",
"password": "aaa"
},
{
"login": "bb",
"password": "bbb"
}
]
Код: Выделить всё
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.LinkedHashMap` from Array value (token `JsonToken.START_ARRAY`)
at [Source: (ByteArrayInputStream); line: 1, column: 1]
Обновление 1
Я изменил метод:
Код: Выделить всё
public class JsonPropertySourceFactory
implements PropertySourceFactory {
private static final Logger LOG = LogManager.getLogger(JsonPropertySourceFactory.class);
@Override
public PropertySource createPropertySource(
String name, EncodedResource resource)
throws IOException {
ObjectMapper mapper = new ObjectMapper();
List usersList = mapper.readValue(resource.getInputStream(), new TypeReference() {});
Map usersMap = new HashMap();
for (int i = 0; i < usersList.size(); i++) {
Map user = usersList.get(i);
usersMap.put("user" + (i + 1), user); // Ключ в формате "user1", "user2" и т.д.
}
System.out.println(usersMap);
return new MapPropertySource("json-property", usersMap);
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... k-and-java
Мобильная версия