Home > other >  Deserialize inner json string property with GSON
Deserialize inner json string property with GSON

Time:05-19

I'm using Springboot and Gson for my backend. I have these two classes in a many to many relation:

Order class

@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table( name = "orders")
public class Order {
    @Id
    @Expose
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Expose
    @NotBlank
    private String poNumber;
    @Expose
    @NotBlank
    private String dimension;
    @Expose
    @NotBlank
    private int initialQuantity;
    @Expose
    @NotBlank
    private int leftQuantity;
    @Expose
    @NotBlank
    private Date startDate;
    @Expose
    @NotBlank
    private Date endDate;
    @Expose
    @SerializedName("status")
    @Enumerated(EnumType.STRING)
    @Column(length = 20)
    private PoStatus status;

    @OneToMany(mappedBy="order")
    private Set<Log> logs;

    @Expose
    @SerializedName("products")
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable( name = "orders_products",
            joinColumns = @JoinColumn(name = "order_id"),
            inverseJoinColumns = @JoinColumn(name = "sap_code"))
    private Set<Product> products = new HashSet<>();

Product Class

@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table( name = "products")
public class Product {
    @Expose
    @Id
    @NotBlank
    private String sapCode;
    @Expose
    @NotBlank
    private String sapCodeDescription;
    @Expose
    private String productData;
}

And this is the service that I use to serve the data to my rest endpoint

public String getAllOrders() {
    List<Order> allOrders = orderRepository.findAll();
    String allOrdersResult = gson.toJson(allOrders);
    return allOrdersResult;
}

And this is the response:

   [
   {
       "id": 1,
       "poNumber": "003100059361",
       "dimension": "INTBKGR",
       "initialQuantity": 200000,
       "leftQuantity": 200000,
       "startDate": "17/08/2022 00:00",
       "endDate": "17/08/2022 00:00",
       "status": "READY",
       "products": [
           {
               "sapCode": "000000000000416234",
               "sapCodeDescription": "1.STUFE 15X",
               "productData": "{\"pieces\": 85, \"mark\": true, \"description\": \"elementum pellentesque quisque porta volutpat erat quisque erat eros viverra eget congue eget\"}"
           }
       ]
   }
]

My aim is to deserialize/escape the productData String property.

I've tried by creating a ProductData class and using the @JsonAdapter annotation, but as far as I understood this annotation Is used when you need to give a custom behaviour to your deserialization, the JSON string in my example is very simple and I don't need any particular logic behind it.

CodePudding user response:

I think you have to declare a class for that and change productData type from string to that class.

CodePudding user response:

I resolved in this way, I think this is NOT a good approach and I hope that there is a more automatic approach to solve this.

Product Class

public class Product {
    @Expose
    @Id
    @NotBlank
    private String sapCode;
    @Expose
    @NotBlank
    private String sapCodeDescription;

    //THIS PROPERTY IS TO SAVE THE JSON IN THE DB
    @NotBlank
    @Column(columnDefinition="TEXT")
    @JsonProperty
    private String productDataColumn;

    //THIS PROPERTY IS TO EXPOSE THE DATA TO THE API
    @Transient
    @Expose
    private ProductData productData;

    public void createProductData() {
        this.productData = new Gson().fromJson(productDataColumn, ProductData.class);
    }
}

ProductData Class

public class ProductData  {
  @Expose
  public int pieces;
  @Expose
  public boolean marcatura;
  @Expose
  public String description;
}

OrderService

public String getAllOrders() {
    List<Order> allOrders = orderRepository.findAll();
    for(Order o : allOrders){
        Product orderProduct = o.getProducts().stream().findFirst().get();
        orderProduct.createProductData();
    }
    String allOrdersResult = gson.toJson(allOrders);
    return allOrdersResult;
}
  • Related