[英]How to Convert JSON to JAVA Object using ObjectMapper?
Java Object Java对象
class B { private String attr; /***** getters and setters *****/ } class A { private String attr1; private String attr2; private Map<String,B> attr3; /***** getters and setters *****/ }
Json Object JSON 对象
json = {attr1 :"val1", attr2 : "val2", attr3 : {attr : "val"}}
How to convert json to java Object (class java contain Map as type of attribute) ?如何将 json 转换为 java 对象(java 类包含 Map 作为属性类型)?
You can use Jackson to do that:您可以使用杰克逊来做到这一点:
//Create mapper instance
ObjectMapper mapper = new ObjectMapper();
//Usea a JSON string (exists other methos, i.e. you can get the JSON from a file)
String jsonString= "{'name' : 'test'}";
//JSON from String to Object
MyClass result= mapper.readValue(jsonString, MyClass .class);
Create a model/POJO which resembles your json structure and then by putting json string in json file you can get java object by using below simple code by using JACKSON dependacy创建一个类似于您的 json 结构的模型/POJO,然后通过将 json 字符串放入 json 文件中,您可以通过使用 JACKSON 依赖项使用以下简单代码获取 java 对象
ObjectMapper mapper = new ObjectMapper();
File inRulesFile = (new ClassPathResource(rulesFileName + ".json")).getFile();
List<Rule> rules = mapper.readValue(inRulesFile, new TypeReference<List<Rule>>() {
});
@RunWith(SpringRunner.class) @SpringBootTest class PostSaveServiceTest { private static final String PATH_TO_JSON = "classpath:json/post-save"; private static final String EXTENSION_JSON = ".json"; @Test void setData() { ObjectMapper objectMapper = new ObjectMapper(); Post post = runParseJsonFile(objectMapper); System.out.println(post); } private Post runParseJsonFile(ObjectMapper objectMapper) { File pathToFileJson = getPathToFileJson(PATH_TO_JSON + EXTENSION_JSON); Post post = null; try { post = objectMapper.readValue(pathToFileJson, Post.class); } catch (IOException e) { System.out.println("File didn't found : " + e); } return post; } private File getPathToFileJson(String path) { File pathToJson = null; try { pathToJson = ResourceUtils.getFile(path); } catch (IOException e) { e.printStackTrace(); } return pathToJson; } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.