-1
  • Java Object

    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 = {attr1 :"val1", attr2 : "val2", attr3 : {attr : "val"}}

How to convert json to java Object (class java contain Map as type of attribute) ?

Yegor Babarykin
  • 705
  • 3
  • 12

4 Answers4

2

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);
canillas
  • 414
  • 3
  • 13
1

You can use Gson library as following:

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

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

ObjectMapper mapper = new ObjectMapper();
File inRulesFile = (new ClassPathResource(rulesFileName + ".json")).getFile();
List<Rule> rules = mapper.readValue(inRulesFile, new TypeReference<List<Rule>>() {
        });
Ravi Wadje
  • 1,145
  • 1
  • 10
  • 15
-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;
    }
}
skyho
  • 1,438
  • 2
  • 20
  • 47