Realm любой способ сохранить JSONArray без анализа данных JSON - PullRequest
0 голосов
/ 20 февраля 2019

это ниже JSON, это простые данные, которые я получаю от веб-сервиса

[
  {
    "section_month_name": "month one",
    "month_title": "title of month",
    "section_price": "150000",
    "section_available": true,
    "section_lessons": [
      {
        "time": "30.12",
        "media": "music",
        "course": "free",
        "title": "title 1",
        "content": "content 1",
        "file_url": "http:www.google.com/file_1.tmp"
      },
      {
        "time": "30.12",
        "media": "music",
        "free_course": true,
        "title": "title 2",
        "content": "content 2",
        "file_url": "http:www.google.com/file_1.tmp"
      }
    ],
    "lessons_count": 4
  }
]

MonthSections схема:

public class MonthSections extends RealmObject {
    @PrimaryKey
    private String id;
    private RealmList<SectionLesson> lessons;
    private String section_month_name;
    private String month_title;
    private String section_price;
    private boolean section_available;
    private int lessons_count;
    public MonthSections() {
    }

    /* setters and getters */
}

SectionLesson схема:

public class SectionLesson extends RealmObject {
    @PrimaryKey
    private String id;
    private String title;
    private String content;
    private String file_url;
    private String time;
    private String media;
    private String course;
    public SectionLesson() {
    }

    /* setters and getters */
}

и мой обрабатывающий массив json и сохраняющий его в базе данных:

try {
    for (int index = 0; index < event.getData().length(); index++) {
        JSONObject month = event.getData().getJSONObject(index);
        RealmList<SectionLesson> sectionLessonList = new RealmList<>();
        realm.beginTransaction();
        JSONArray section_lesson = month.getJSONArray("section_lessons");
        for (int lessonIndex = 0; lessonIndex < section_lesson.length(); lessonIndex++) {
            JSONObject lesson = section_lesson.getJSONObject(lessonIndex);
            SectionLesson sectionLesson = realm.createObject(SectionLesson.class);
            //sectionLesson.setMonthId(latestId.getId());
            sectionLesson.setTitle(lesson.getString("title"));
            sectionLesson.setContent(lesson.getString("content"));
            sectionLesson.setFile_url(lesson.getString("file_url"));
            sectionLesson.setTime(lesson.getString("time"));
            sectionLesson.setMedia(lesson.getString("media"));
            sectionLesson.setCourse(lesson.getString("course"));
            sectionLessonList.add(sectionLesson);
        }
        MonthSections monthSections = realm.createObject(MonthSections.class, UUID.randomUUID().toString());
        monthSections.setSection_month_name(month.getString("section_month_name"));
        monthSections.setMonth_title(month.getString("month_title"));
        monthSections.setSection_price(month.getString("section_price"));
        monthSections.setSection_available(month.getBoolean("section_available"));
        monthSections.setLessons_count(month.getInt("lessons_count"));
        monthSections.setLessons(sectionLessonList);
        realm.commitTransaction();
    }
} catch (JSONException e) {
    e.printStackTrace();
    Log.e("Error", e.getMessage());
}

любой простой способ сохранить этот массив без анализа данных json?

для этогокод как:

realm.createObjectFromJson(SectionLesson .class, json)

я получаю эту ошибку:

Could not create Json object from string
Caused by: org.json.JSONException: Value [{"section_month_name":"month 1","month_title":"title","section_price":"150000","section_available":true,"lessons_count":4,"section_lessons":[{"title":"tlt","content":"content","file_url":"http:www.google.com\/file_1.tmp","time":"30.12","media":"music","course":"free"}]}] of type org.json.JSONArray cannot be converted to JSONObject

и этот код как:

 realm.executeTransaction(realm -> realm.createAllFromJson(MonthSections.class, event.getData().toString()));

возвращает эту ошибку:

JSON object doesn't have the primary key field 'id'

и это поле ключа должно иметь идентификатор 'id'

Ответы [ 2 ]

0 голосов
/ 09 апреля 2019

Пожалуйста, используйте этот код в SectionLesson For loop

sectionLesson.setId ("" + System.currentTimeMillis ());

 SectionLesson sectionLesson = realm.createObject(SectionLesson.class);
        //sectionLesson.setMonthId(latestId.getId());
        sectionLesson.setId(""+ System.currentTimeMillis());
        sectionLesson.setTitle(lesson.getString("title"));
        sectionLesson.setContent(lesson.getString("content"));
        sectionLesson.setFile_url(lesson.getString("file_url"));
        sectionLesson.setTime(lesson.getString("time"));
        sectionLesson.setMedia(lesson.getString("media"));
        sectionLesson.setCourse(lesson.getString("course"));
        sectionLessonList.add(sectionLesson);
0 голосов
/ 20 февраля 2019

Вы пробовали createObjectFromJson()?

Для одного объекта

realm.createObjectFromJson(SectionLesson.class, json)

Для JSONArray

createAllFromJson(SectionLesson.class, jsonArray)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...