RoboSpice persist JSON array with OrmLite

删除回忆录丶 提交于 2019-12-01 06:05:14

I've found a work around to this problem. I added an extra result object which holds the array of objects. Off course this is only possible if you are able to manipulate the JSON. Still not really happy with this because I have introduce an useless class to my model.

So my the JSON looks like:

{ 
    "id": 1,
    "result":[{"id": 1, "title": "Test 1"},{"id": 2, "title": "Test 3"},{"id": 3, "title": "Test 3"}]
}

And I added the following class to hold the JSON result:

@DatabaseTable
public class FooResult {
    @DatabaseField(id = true)
    private int id;
    @ForeignCollectionField(eager = false)
    private Collection<Foo> result;

    // getters and setters
    ...
}

Also added the foreign relation the the Foo class:

@DatabaseTable
public class Foo {
    @DatabaseField(id = true)
    private int id;
    @DatabaseField
    private String title;
    @DatabaseField(foreign = true)
    private FooResult result;

    // getters and setters
    ...
}

I have found the way which works for me. I did not changed my json.

@DatabaseTable(tableName = SampleContract.Contributor.TABLE)
public class Contributor {

    @DatabaseField(generatedId = true, columnName = SampleContract.Contributor._ID)
    private int id;

    @DatabaseField(columnName = SampleContract.Contributor.LOGIN)
    public String login;

    @DatabaseField(columnName = SampleContract.Contributor.CONTRIBUTIONS)
    public int contributions;

    @DatabaseField(foreign = true)
    private ContributorsResult result;

    @SuppressWarnings("serial")
    @DatabaseTable(tableName = "contributor_list")
    public static class ContributorsResult extends ArrayList<Contributor> {

        @DatabaseField(id = true)
        private int id = 0;


        @ForeignCollectionField(eager = false)
        private Collection<Contributor> result = this;

        public Collection<Contributor> getResult() {
            return result;
        }

        public void setResult(Collection<Contributor> result) {
            if (result != null) {
                this.clear();
                this.addAll(result);
            }
        }

    }


}
Simon

I struggled with this the whole of today and finally figured how to save a JSON array into a SQLite database using Robospice Spring Android without modifying the JSON.

This is my post JSON array returned from my server:

[
{
"id": "5573547af58cd75df03306cc",
"name": "Simon",
"postheader": "First Post"
},
{
"id": "55735475f58cd75df03306cb",
"name": "Tyron",
"postheader": "Second Post"
}
]

This is similar to the JSON in this question:

[{"id": 1, "title": "Test 1"},{"id": 2, "title": "Test 3"},{"id": 3, "title": "Test 3"}]

Step 1:

You will need to create 2 classes on the android side.

One will be the normal object that you want to save from the array. In my case, I have an object called "Post" and my server returns an array of "Post".

@DatabaseTable(tableName = "post")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Post implements Serializable {
    @DatabaseField(id = true)
    private String id;
    @DatabaseField
    private String name;
    @DatabaseField
    private String postheader;
    @DatabaseField(foreign = true,foreignAutoCreate = true,foreignAutoRefresh = true)
    private EmbedPost posts;

The other object will be a wrapper object that wraps over the array, I called mine "EmbedPost".

@DatabaseTable
public class EmbedPost implements Serializable {
    @DatabaseField(allowGeneratedIdInsert=true, generatedId=true)
    private int ID;
    @ForeignCollectionField(eager = false)
    private Collection<Post> posts;

By defining an int called ID in my EmbedPost class, I'm effectively creating a object that if I converted to JSON would look like this:

{"id": 1, "posts": [
{
"id": "5573547af58cd75df03306cc",
"name": "Simon",
"postheader": "First Post"
},
{
"id": "55735475f58cd75df03306cb",
"name": "Tyron",
"postheader": "Second Post"
}
]}

This is effectively a JSON string that looks very similar to what Uipko used in his solution.

{ 
    "id": 1,
    "result":[{"id": 1, "title": "Test 1"},{"id": 2, "title": "Test 3"},{"id": 3, "title": "Test 3"}]
}

Step 2:

You now persist it using SpringAndroidSpiceService.

public class AndroidSpiceService extends SpringAndroidSpiceService {
    private static final int WEBSERVICES_TIMEOUT = 10000;

    @Override
    public CacheManager createCacheManager( Application application ) {
        CacheManager cacheManager = new CacheManager();
        List< Class< ? >> classCollection = new ArrayList< Class< ? >>();

        // add persisted classes to class collection
        classCollection.add(EmbedPost.class);
        classCollection.add( Post.class );
        // init
        RoboSpiceDatabaseHelper databaseHelper = new RoboSpiceDatabaseHelper( application, "sample_database.db", 3);
        InDatabaseObjectPersisterFactory inDatabaseObjectPersisterFactory = new InDatabaseObjectPersisterFactory( application, databaseHelper, classCollection );
        cacheManager.addPersister( inDatabaseObjectPersisterFactory );
        return cacheManager;
    }

    @Override
    public RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // set timeout for requests

        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setReadTimeout( WEBSERVICES_TIMEOUT );
        httpRequestFactory.setConnectTimeout( WEBSERVICES_TIMEOUT );
        restTemplate.setRequestFactory( httpRequestFactory );

        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        final List<HttpMessageConverter< ? >> listHttpMessageConverters = restTemplate.getMessageConverters();

        listHttpMessageConverters.add( mappingJackson2HttpMessageConverter  );
        restTemplate.setMessageConverters( listHttpMessageConverters );
        return restTemplate;
    }

}

Be sure to add both the EmbedPost.class and Post.class to your classCollection as ORMLite cannot do its work without you persisting both. You had used ForeignKeys when you wrote up your objects and these foreign keys have to tie to something so therefore both classes must persist.

If you run into trouble, try using the logcat to figure it out. You might have to read all the messages and not just the error ones. See my post here to see how to read all logcat messages:

Robospice storing object that extends ArrayList in database via Ormlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!