Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Java add empty array to JSON object

Tags:

java

json

arrays

I'm stuck with the following problem.

My backend (Java sevlet) returns from a database all the fields from a single record/document from a MongoDB. This JSON string is sent to the frontend where some magic is done.

This is done with the following code:

public String getDocumentJSON(int id) {
    DBCollection collection = database.getCollection("People");
    BasicDBObject query = new BasicDBObject();
    query.put("id", id);
    DBCursor cur = collection.find(query);
    DBObject one = cur.next();  
    return JSON.serialize(one);
}

The frontend requires a field: photos[]

New records/documents are created with this field. (it's an array with photo filenames). The older records/documents do not have this field, which causes the frontend to break.

To prevent this I would want to add the array: photos[] to the JSON before sending it to the frontend. But I'm not to sure how I add this array to the JSON.

Preferably my code would check to see if the JSON or DBObject has the field photos[] if it does, then nothing is done, if it doesn't contain this field. Then it is added.

The frontend just needed the photos[] even if it's empty that's no problem.

I would rather fix this in the backend that in the frontend.

like image 467
Steven Filipowicz Avatar asked May 28 '26 13:05

Steven Filipowicz


1 Answers

Something like this should work:

DBObject one = cur.next();  

if (one.get("photos") == null)
  one.put("photos", new Object[0]);

return JSON.serialize(one);
like image 195
Thilo Avatar answered May 31 '26 07:05

Thilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!