0

I'm using Postman to test REST Web API and I have a method that receives this object:

public class NewShipmentDto implements Serializable {
  private String description;
  private Long senderId;
  private Long receiverId;
  private byte[] packageImage;
  private CommissionPaidBy commissionPaidBy;
  private Long senderPaymentMethod;
  private LocationDto senderLocation;
  private LocationDto receiverLocation;

// + constructors and gets/sets
}

So the body of my POST needs to be something like this:

{
    "description":"Libros",
    "senderId":1,
    "receiverId":1,
    "commissionPaidBy":"BOTH",
    "senderPaymentMethod":1,
    "senderLocation":
    {
        "latitud":100,
        "longitud":100
    },
    "receiverLocation":
    {
        "latitud":100,
        "longitud":100
    }
}

But I also need to send the file so it can be transformed to a byte []. The thing is if I use form data to pass the file how do I send this bits:

"receiverLocation":
{
    "latitud":100,
    "longitud":100
}

Is it possible to send nested json in the form data?

This is my POST method, I haven't added the logic of reading the file yet:

@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response addShipment(String shipment) throws EnviosYaException {
    Gson gson = new Gson();
    NewShipmentDto newShipmentDto = gson.fromJson(shipment, NewShipmentDto.class);
    NewShipmentResponseDto response = shipmentServices.addShipment(newShipmentDto);
    return Response.ok(gson.toJson(response)).build();
}

If necessary I could change the structure of the json to avoid having nested json, but I would like to know if it's possible first. Thanks

moondaisy
  • 4,303
  • 6
  • 41
  • 70

1 Answers1

0

It looks like you are using JAX-RS for the REST API. For your use case multipart/format-data content-type is more appropriate. Please have a look at this JAX-RS question.

Or

If you like keep the JSON structure intact, you can store the base64 encoded data in a string for the image field. The model would looks like.

public class NewShipmentDto implements Serializable {
  private String description;
  private Long senderId;
  private Long receiverId;
  private String encodedPackageImage;
  private CommissionPaidBy commissionPaidBy;
  private Long senderPaymentMethod;
  private LocationDto senderLocation;
  private LocationDto receiverLocation;

  // + constructors and gets/sets
}
chinoy
  • 172
  • 1
  • 13