如何使用ObjectMapper将JSON转换为JAVA对象?

时间:2017-11-09 08:05:30

标签: java json objectmapper

  • 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对象

    json = {attr1 :"val1", attr2 : "val2", attr3 : {attr : "val"}}

如何将json转换为java Object(类java包含Map作为属性类型)?

4 个答案:

答案 0 :(得分:1)

你可以使用Jackson来做到这一点:

//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);

答案 1 :(得分:0)

您可以使用Gson库,如下所示:

// representation string for your Json object
String json = "{\"attr1\": \"val1\",\"attr2\": \"val2\",\"attr3\": {\"attr\": \"val\"}}"; 

Gson gson = new Gson();
A a = gson.fromJson(json, A.class);

答案 2 :(得分:0)

创建一个类似于您的json结构的模型/ POJO,然后通过将json字符串放入json文件中,可以通过使用下面的简单代码(通过使用杰克逊相关性)来获取Java对象

ObjectMapper mapper = new ObjectMapper();
File inRulesFile = (new ClassPathResource(rulesFileName + ".json")).getFile();
List<Rule> rules = mapper.readValue(inRulesFile, new TypeReference<List<Rule>>() {
        });

答案 3 :(得分:-1)

@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;
    }
}