Hi I am trying to parse a JSON that I have saved in a resource folder and test it. So I took these steps for now.
DataLoader.java
@Service
public class DataLoader {
private static ObjectMapper objectMapper = defaultObjectMapper();
private static ObjectMapper defaultObjectMapper(){
ObjectMapper defaultObjectMapper = new ObjectMapper();
//defaultObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return defaultObjectMapper;
}
public static JsonNode parse(String str) throws IOException {
return objectMapper.readTree(str);
}
public static <A> A fromJason(JsonNode node, Class<A> clazz) throws JsonProcessingException {
return objectMapper.treeToValue(node, clazz);
}
}
DataLoaderTest.java
public class DataLoaderTest {
@Value("classpath:data/novo.json")
Resource jsonSource;
//private String jsonSource = "{\"title\":\"new book\"}";
@Test
public void parse() throws IOException {
JsonNode node = DataLoader.parse(jsonSource);
assertEquals(node.get("title").asText(), "new book");
}
@Test
public void fromJson() throws IOException {
JsonNode node = DataLoader.parse(jsonSource);
Fruit pojo = DataLoader.fromJason(node, Fruit.class);
System.out.println("Pojo title " + pojo.title);
}
}
So when I test it with //private String jsonSource = "{\"title\":\"new book\"}";
everything is working fine.
When I try to load JSON file from resources folder I am getting error:
error: incompatible types: Resource cannot be converted
to String JsonNode node = ApxDataLoader.parse(jsonSource);
Any help highly appreciated.
Aucun commentaire:
Enregistrer un commentaire