Я пытаюсь создать JSON-запрос к целевому API из моих java-классов и заметил, что при использовании библиотеки GSON 2.8.5 иногда двойные кавычки для некоторых значений ключей отсутствуют или не помещаются, а также могут отсутствовать некоторые символыв некоторых логических значениях, например, «false» отображается как «flse» для ключа обязательного_символа_читания.Это происходит редко, но вызывает проблемы на принимающем API.Это программное обеспечение используется для отправки в хранилище информации о коробках и элементах, которые они получат.
Вот как я строю объект GSON в своем коде:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
Я создалмаленькая функция для удаления кавычек и строк из всех строк, например:
/**
* Remove special characters from String.
*
* @param string The string to be modified.
* @return String Returns the modified string.
*/
public String removeChars(String string)
{
return string.replaceAll("\\n", "").replaceAll("\\r", "").replace("'", "").replace("\"", "").replace(":", "");
}
Мой принимающий класс (который будет преобразован в JSON) выглядит следующим образом:
public class Receiving
// Variables.
private Document document;
private List<Resource> resources;
// *** CONSTRUCTORS ***
/**
* Default constructor.
*
* @param document The document with all the data of the receiving.
* @param resources The resources associated with this document.
*/
public Receiving(Document document, List<Resource> resources)
{
this.document = document;
this.resources = resources;
}
Класс документа:
public class Document
// Variables.
private String id, type, date;
private Store3 store;
private Source source;
private Transporter transporter;
// *** CONSTRUCTORS ***
/**
* Default constructor.
*
* @param id The ID of the document.
* @param type The type of the document.
* @param date The date of the document.
* @param store The destination store.
* @param source The origin store.
* @param transporter The transporter of the boxes.
*/
public Document(String id, String type, String date, Store3 store, Source source, Transporter transporter)
{
this.id = id;
this.type = type;
this.date = date;
this.store = store;
this.source = source;
this.transporter = transporter;
}
Класс ресурса:
public class Resource
// Variables.
private String type;
private Data3 data;
private List<Resource> resources;
// *** CONSTRUCTORS ***
/**
* Default constructor.
*
* @param type The type of the resource.
* @param data The contents of the resource.
* @param resources The list of the items in a container.
*/
public Resource(String type, Data3 data, List<Resource> resources)
{
this.type = type;
this.data = data;
this.resources = resources;
}
public Data3 getData() {
return data;
}
Класс данных, содержащий информацию о контейнере или элементе в контейнере:
public class Data3
// Variables.
private String id, sku, bar_code, name, description;
private int quantity;
private Metadata metadata;
// *** CONSTRUCTORS ***
/**
* Default constructor.
*
* @param id The ID of the resource.
* @param sku The SKU in the resource.
* @param bar_code The bar code of the resource or the SKU.
* @param name The name of the SKU.
* @param description The description of the SKU.
* @param quantity The quantity of the SKU.
* @param metadata The meta data of the container or the item.
*/
public Data3(String id, String sku, String bar_code, String name, String description, int quantity, Metadata metadata)
{
this.id = id;
this.sku = sku;
this.bar_code = bar_code;
this.name = name;
this.description = description;
this.quantity = quantity;
this.metadata = metadata;
}
public String getId() {
return id;
}
Метаданныекласс:
public class Metadata
// Variables.
private int doc_id;
private String source_type, source_id;
private int item_request_id;
private boolean mandatory_item_read;
// *** CONSTRUCTORS ***
/**
* Default constructor.
*
* @param doc_id The associated document of the receiving.
* @param source_type The source store or warehouse of the receiving.
* @param source_id The source name or reference.
* @param item_request_id The line of the document for this SKU.
* @param mandatory_item_read The indication if the scanning of the bar code of the SKU is mandatory or not.
*/
public Metadata(int doc_id, String source_type, String source_id, int item_request_id, boolean mandatory_item_read)
{
this.doc_id = doc_id;
this.source_type = source_type;
this.source_id = source_id;
this.item_request_id = item_request_id;
this.mandatory_item_read = mandatory_item_read;
}
Пример кода, в котором я добавляю элементы и контейнеры:
// Add SKU to this box.
skuMap.get(result.getString("BOX")).add( new Resource( "ITEM",
new Data3( result.getString("SKU"),
result.getString("SKU"),
result.getString("BARCODE"),
sts.removeChars(result.getString("SKU_DESC")),
sts.removeChars(result.getString("SKU_DESC")),
result.getInt("QUANTITY"),
new Metadata( 0,
null,
null,
result.getInt("RECEIPT_LINE"),
false)),
null));
}
}
// Reset cursor.
result.beforeFirst();
// Gather all boxes to the stores.
while(result.next())
{
// Check if the store already exists.
if(storesMap.get(result.getString("STORE")) == null)
{
// Create new list.
storesMap.put(result.getString("STORE"), new ArrayList<Resource>());
// Add the box to this store.
storesMap.get(result.getString("STORE")).add( new Resource( "CONTAINER",
new Data3( result.getString("MOVE_WEBPORTAL"),
null,
result.getString("BOX"),
null,
null,
1,
new Metadata( result.getInt("DOC_ID"),
result.getString("FROM_LOC_TYPE"),
result.getString("FROM_WHAREHOUSE"),
0,
false)),
skuMap.get(result.getString("BOX"))));
lastBox = result.getString("BOX");
}
Вот что происходит в некоторых строках при создании JSON.Двойные кавычки отсутствуют для окончания ключа SKU ("sku:" 153587_BKL "). Я понятия не имею, почему это происходит с некоторыми ключами, но в 99% элементов и контейнеров все идеально. Есть только несколькоошибочно сгенерированы как этот пример, но этого достаточно, чтобы сделать мой JSON недействительным. Сами файлы могут быть довольно большими, от 500 КБ до 6 МБ.
{
"type": "ITEM",
"data": {
"id": "153587_BKL",
"sku:" 153587_BKL "," bar_code ":" 5606420089103 "," name ":" Travel Nylon Gym SCARLETTBlackL "," description ":" Travel Nylon Gym SCARLETTBlackL "," quantity ":4," metadata ":{" doc_id ":0," item_request_id ":36," mandatory_item_read ":false}}},{" type ":" ITEM "," data ":{" id ":" 166784_ECL "," sku ":" 166784_ECL "," bar_code ":" 5606428695535 "," name ":" Printed Scarf Valentine Day Ecru L "," description ":" Printed Scarf Valentine Day Ecru L "," quantity ":6," metadata ":{" doc_id ":0," item_request_id ":38," mandatory_item_read ":false}}},{" type ":" ITEM "," data ":{" id ":" 160330_NVM "," sku ":" 160330_NVM "," bar_code ":" 5606428601512 "," name ":" Pashmina PERMANENT Navy M "," description ":" Pashmina PERMANENT Navy M "," quantity ":2," metadata ":{" doc_id ":0," item_request_id ":37," mandatory_item_read ":false}}}]},{" type ":" CONTAINER "," data ":{" id ":" 910388571 "," bar_code ":" G90003303230 "," quantity ":1," metadata ":{" doc_id ":46768577," source_type ":" W "," source_id ":" CLC "," item_request_id ":0," mandatory_item_read ":false}}," resources ":[{" type ":" ITEM "," data ":{" id ":" 164859_BKM "," sku ":" 164859_BKM "," bar_code ":" 5606428662841 "," name ":" Crossbody Bag FÉNIX Black M "," description ":" Crossbody Bag FÉNIX Black M "," quantity ":2," metadata ":{" doc_id ":0," item_request_id ":7," mandatory_item_read ":false}}},{" type ":" ITEM "," data ":{" id ":" 166217_BNU "," sku ":" 166217_BNU "," bar_code ":" 5606428683228 "," name ":" Medium Width Belt GENERAL BELTS Brown U "," description ":" Medium Width Belt GENERAL BELTS Brown U "," quantity ":1," metadata ":{" doc_id ":0," item_request_id ":14," mandatory_item_read ":false}}},{" type ":" ITEM "," data ":{" id ":" 160326_BKM "," sku ":" 160326_BKM "," bar_code ":" 5606428601406 "," name ":" Scarf Movel Festa Black M "," description ":" Scarf Movel Festa Black M "," quantity ":3," metadata ":{" doc_id ":0," item_request_id ":4," mandatory_item_read ":false}}},{" type ":" ITEM "," data ":{" id ":" 164849_RDM "," sku ":" 164849_RDM "," bar_code ":" 5606428662834 "," name ":" Backpack FÉNIX Red M "," description ":" Backpack FÉNIX Red M "," quantity ":2," metadata ":{" doc_id ":0," item_request_id ":8," mandatory_item_read ":false}}},{" type ":" ITEM ",data": {
"id": "164573_NVM",
"sku": "164573_NVM",
"bar_code": "5606428658523",
"name": "Box Bag GATE Navy M",
"description": "Box Bag GATE Navy M",
"quantity": 1,
"metadata": {
"doc_id": 0,
"item_request_id": 10,
"mandatory_item_read": false
}
}
}
Любая помощь, пытающаяся понять эту проблему,высоко ценится.