amili
amili

Reputation: 1

How to read JSON String in Spring data and write to a database MySql

I have the JSON file and I want to persist it into Mysql database can anyone give me the steps to follow with the spring-data to do this, my JSON looks like this i created a modele with 3 class named like this Portal.java,Spaces.java,Indicators.java

{
"portalName":"office360",
"spaces": [
    {
        "spaceName": "Modèle d'Espace collaboratif",
        "indicators": [
            {
                "indicatorName": "Created content",
                "indicatorCounter": "0"
            },

            {
                "indicatorName": "answers reader",
                "indicatorCounter": "0"
            }
        ]
    }, 
    {
        "spaceName": "Espace de Travail par Defaut",
        "indicators": [
            {
                "indicatorName": "Created content",
                "indicatorCounter": "0"
            },
            {
                "indicatorName": "answers reader",
                "indicatorCounter": "0"
            }
        ]
    }
]}

Upvotes: 0

Views: 1476

Answers (2)

Alexius DIAKOGIANNIS
Alexius DIAKOGIANNIS

Reputation: 2584

You need to use the RestTemplate in Spring.

The steps are

  1. If you are too lazy to create the classes that will be mapped to your json object, then you can use this website http://pojo.sodhanalibrary.com/ it will create it for you. Lets assume that the class created is Page.class
  2. Create a Repository class like

    import org.springframework.web.client.RestTemplate;
    
    @Repository
    public class OfficeRepository{
    
      public Page getSomething() {
        RestTemplate restTemplate = new RestTemplate();
        Page page = restTemplate.getForObject("http://your-url-goes-here", Page.class);
        return page;
      }
    }
    

This will return your JSON contents into the Page object created.

This was the hard part. The easy part is to save it to the DB. Please use this guide by spring https://spring.io/blog/2011/02/10/getting-started-with-spring-data-jpa/ in order to save it and if you have any questions feel free to ask.

Upvotes: 0

Bronius Janonis
Bronius Janonis

Reputation: 75

If you have file wit JSON type data in it and have in Back-End three classes which should be filled with Json Data so I suggest the following:

  1. use Gson library: https://github.com/google/gson
  2. List item
  3. Create DTO classs (consisting all three classes)
  4. With file read get data from file to String: String fileString = new String(Files.readAllBytes(Paths.get("manifest.mf")), StandardCharsets.UTF_8);

  5. Then combine Gson library, DTO class and this line: Data data = new Gson().fromJson(fileString, Data.class);

Now you will have DTO object filled with data

Upvotes: 1

Related Questions