Jackson + ORMLite – JSON POJO SQLITE – Step1 : Convert JSON to POJOs



Jackson + ORMLite – JSON POJO SQLITE – Step1 : Convert JSON to POJOs

0 0


android-orm-presentation


On Github rorlig / android-orm-presentation

Jackson + ORMLite

Gaurav Gupta

JSON <-> POJO <-> SQLITE

  • Http Request/Response Objects have JSON strings/objects in body
  • Android Objects(Java) need to convert JSON strings to Java Objects
  • And Persist them in local database (SQLITE)

JSON

						{ "firstName" : "Gaurav","lastName" : "Gupta"}
						
						

POJO

						class User {String firstName; String lastName;}
						
						

SQLITE

						 CREATE TABLE User (first_name VARCHAR(255), last_name VARCHAR(255))
						
						

Step1 : Convert JSON to POJOs

  • Approach 1: Parse the JSON string and manually create Objects

    Too much work

  • Approach 2: Use a library - such as Jackson (much faster) or GSON

    Ah much better

Step 2 : Persisting POJOs to DB

  • Approach 1: Interact with SQLITE directly

    								 	INSERT INTO TABLE USERS VALUES ("GAURAV", "GUPTA");
    								 
  • Approach 2: Use an ORM library such as ORMLITE

    								 	User user = new User(“Gaurav”, “Gupta”); user.save();
    								 

Use case

Consider a blog where a user can create posts and each post can have many comments. The comments are made by a logged in user. In addition user has some settings.

Relationship between the data

  • One-to-One relationship

    • User and Settings

  • One-to-Many Relationships

    • Blog and Posts

    • Blog and Comments

  • Many-to-Many Relationship

    • Blog and Users

The class model

						
	class Blog{
		private List<Post> posts;
		private List<User> users;

	}

	class Post {
		private List<Comment> comments;
	}

	class User {
		private List<Blog> blogs;
		private Setting settings;
	}

	class Comment {
		private Post post;
	}