-2

lets say I'm creating an app to browse reddit using their API. I'm getting a json response containing submissions, which I plan to populate a listview with. My question is how I should save this data? Should I create a bunch of objects or is there a better way to save it? I will need to be able to identify which submission the user clicks on so they can view the full thread etc.

timsuldat
  • 138
  • 11
  • I suggest you to use SQLiteDatabase + ContentProvider + Loader. More information can be easily found by searching for these keywords. – Lingviston Jan 18 '16 at 20:44
  • 1
    I'd use Realm for such kind of prototyping. It requires much less effort to start compared to SQLite + ContentProvider + Loader. They have quite nice support for JSON as well. Go to their website to learn more - https://realm.io/. – Mateusz Herych Jan 18 '16 at 20:47
  • 1
    Possible duplicate of [how to save data from json in sqlite in android](http://stackoverflow.com/questions/6563118/how-to-save-data-from-json-in-sqlite-in-android) – pixel Jan 18 '16 at 20:49

3 Answers3

2

I use GSON to deserialize from json object to java object. Jackson is another json parser for java. To use GSON:

  1. Add the GSON library in your build.gradlecompile 'com.google.code.gson:gson:2.3.1'

  2. Create your JAVA model object that matches up with the json object.

  3. Call new GsonBuilder().create().fromJson({json string}, {JAVA model}.class);

Now for saving it, it depends where you want to save it to. If you are fine with saving it to disk via SharedPreferences, you can always serialize it back to the JSON String/Object with:

String json = new GsonBuilder().create().toJson(this);
Jason Grife
  • 1,197
  • 11
  • 14
  • So if i need to store the raw JSON Response in a file not SharedPreferences but a JSON file, then i need to map json response to Java Objects and then need to serialize them and get a string as you described in one line and then store this response string in a json file or i just need to store jsonresponse that i got from retrofit via respose.body().toString method to a file. will these two be the same approach? – Jay Dangar Sep 20 '18 at 18:45
  • 1
    Yes, they will be one in the same. The response.body is json as a string, which can be deserialized to a java object (via GSON library as described above) and then can be serialized back to the json as a string. – Jason Grife Sep 21 '18 at 20:32
  • @Json Grife, Thanks man that worked. – Jay Dangar Sep 23 '18 at 05:50
0

Use some library to handle the deserializing for you. Checkout Retrofit / Volley. Makes life much simpler.

shiladitya
  • 2,290
  • 1
  • 23
  • 36
0

What you get from the server is just text. So you can save it all to a text file. No objects. No serializing. You better spend your time else.

greenapps
  • 11,154
  • 2
  • 16
  • 19