Search code examples
javajsonspringjpa

How to map JSON in a Java object


I'm trying to transform this JSON in a Java object. But I'm struggling with this conversion.

{
    "id": "c01cede4-cd45-11eb-b8bc-0242ac130003",
    "publisherId": "nintendo",
    "name": "Mario",
    "timePlayed": {
        "2023-05-01": 10,
        "2023-05-02": 2,
        "2023-05-03": 3,
        "2023-05-04": 4
    }
}

First, I created a class named GameData and I was able to save the first 3 parameters with no problem at all.
My difficult is with parameter timePlayed. I tried to create another class named TimePlayed, using the annotation Entity–relationship model but I have no success with that. Also, I tried to use a Map instead using the object TimePlayed but it did not work as well.
As you can see, inside the timePlayed is a date and an integer.
This is the code that I have while writing this question:

Class GameData:

@Table(name = "GAME_DATA")
@Entity
@Data
public class GameData {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private String gameDataId;

    private String publisherId;
    private String name;

    private Map<Date, String> timePlayed;


}

Class TimePlayed

@Table(name = "TIME_PLAYED")
@Data
@Entity
public class TimePlayed {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "id", nullable = false)
    private Long id;

    private Map<String, Integer> playedDateAndTime;

}

My guess that using a second class is not the best approach but this what I was capable to do so far and, of course, is not working at all.
I got a some errors like:

  • Object references an unsaved transient instance - save the transient instance before flushing hibernate JPA
  • 'Basic' attribute type should not be a map

Solution

  • I was able to resolve my problem using this the class this way:

    @Table(name = "GAME")
    @Entity
    @Data
    public class Game {
    
        @Id
        @GeneratedValue(strategy = GenerationType.UUID)
        private String gameDataId;
    
        private String publisherId;
        private String name;
    
        @ElementCollection
        @MapKeyColumn(name = "date")
        @Column(name = "time_played")
        @DateTimeFormat(pattern = "yyyy/mm/dd")
        private Map<LocalDate, Integer> timePlayed;
    
    }
    

    This way, I could save and show the JSON the way I need.