2017-06-24 51 views
0

我使用郵差測試REST的Web API發送圖像文件和JSON和我有收到此對象的一個​​方法:郵差 - 在POST

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 
} 

所以我的文章的身體需要是這樣的這個:

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

但我也需要發送文件,以便它可以轉換爲byte []。問題是,如果我使用表單數據傳遞文件我怎麼發送此位:

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

是否有可能在發送表單數據的嵌套JSON?

這是我POST方法,我還沒有添加邏輯讀取文件尚未:

@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(); 
} 

如果有必要我可以改變JSON的結構,以避免嵌套的JSON,但我想知道是否有可能。 謝謝

回答

0

它看起來像你使用JAX-RS的REST API。對於你的用例multipart/format-data內容類型更合適。 請看看JAX-RS question

或者

如果你喜歡保持JSON結構完好,你可以存儲在圖像字段中輸入字符串編碼數據以base64。模型看起來像。

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 
}