В моем случае это был ArrayList классов POJO. Примечание
private String mNoteTitle;
private int mFingerIndex;
private Point mNoteCoordinates;
public Note(String noteTitle, int fingerIndex, Point noteCoordinates) {
this.mNoteTitle = noteTitle;
this.mFingerIndex = fingerIndex;
this.mNoteCoordinates = noteCoordinates;
}
Как указано в руководстве, JSONObject поддерживает только следующие типы: Object: JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL или null. Не может быть NaNs или бесконечности. Итак, я должен разбить свой класс Note на поддерживаемые объекты.
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
for(Note note: chordShape.getNotes()){
JSONObject singleNoteJsonObject = new JSONObject();
try {
singleNoteJsonObject.put(SHAPE_NOTE_TITLE, note.getNoteTitle());
singleNoteJsonObject.put(SHAPE_NOTE_FINGER_INDEX, note.getFingerIndex());
singleNoteJsonObject.put(SHAPE_NOTE_X, note.getNoteCoordinates().x);
singleNoteJsonObject.put(SHAPE_NOTE_Y, note.getNoteCoordinates().y);
} catch (JSONException e){
e.printStackTrace();
}
jsonArray.put(singleNoteJsonObject);
}
Упакуйте созданный массив в JSONObject.
try {
json.put(SHAPE_NOTES, jsonArray);
Log.i(TAG, json.toString());
} catch (JSONException e){
e.printStackTrace();
}
Создать строку.
String notesList = json.toString();
Поместите созданную строку в ContentValues, потому что в моем случае это приложение для Android
if(notesList.length() > 0){
contentValues.put(DatabaseHelper.SHAPE_NOTES_LIST, notesList);
}
И когда я должен прочитать значения из базы данных SQLite.
ArrayList<Note> notes = new ArrayList<>();
while(cursor.moveToNext()){
JSONObject jsonNotes = null;
try {
jsonNotes = new JSONObject(cursor.getString(cursor.getColumnIndex(DatabaseHelper.SHAPE_NOTES_LIST)));
} catch (JSONException e){
e.printStackTrace();
}
if(jsonNotes != null){
Log.i(TAG, jsonNotes.toString());
JSONArray jsonArray = jsonNotes.optJSONArray(SHAPE_NOTES);
for(int i = 0; i < jsonArray.length(); i++){
Note note = null;
JSONObject arrayObject = null;
try {
arrayObject = jsonArray.getJSONObject(i);
} catch (JSONException e){
e.printStackTrace();
}
if(arrayObject != null){
try {
note = new Note(
arrayObject.getString(SHAPE_NOTE_TITLE),
arrayObject.getInt(SHAPE_NOTE_FINGER_INDEX),
new Point(
arrayObject.getInt(SHAPE_NOTE_X),
arrayObject.getInt(SHAPE_NOTE_Y)
)
);
} catch (JSONException e){
e.printStackTrace();
}
}
if(note != null){
notes.add(note);
}
}
}
}
cursor.close();