我正在开发一个Android项目,目前正在尝试弄清楚如何将包含引用周期的JSON
中的某些API
反序列化为对象图,然后我可以操作并存储在数据库中。让我举个例子:
{
"id": "24",
"name": "Bob",
"friends": [
{
"id": "13",
"name": "Alice",
"friends": [
{
"id": "24" // and we have a circular reference
}
]
}
]
}
此处,名为Bob
的人物对象是人Alice
的朋友,而Alice
则是Bob
的朋友。由于关系是递归的,Alice
与Bob
的朋友关系不再被视为完整的人物对象,只提供了他的id
。
您使用哪些工具来执行上述步骤?我尝试使用Jackson实现对象映射部分但未能找到循环要求的解决方案。我发现ongoing discussion有关此主题的内容提到JSOG可能会有所帮助,但我们的API已修复且不符合JSOG。
基本上我正在寻找的是像Android的RestKit(iOS框架)。
答案 0 :(得分:4)
修复API后,我会以这种方式实现它:
从数据库的角度来看,我有2个表 - UserTable 和 RelationsTable ,以保留好友图的所有边缘:
即。 的想法是将用户保留在一个表及其关系表中的关系。它还允许稍后在其上添加一些额外的逻辑(例如,用户隐藏他的连接或阻止某人等 - 图形的任何可能的边缘)。此外,可以缓解循环引用的问题。
作为从服务中检索数据的框架&解析jsons,我会使用Retrofit。
首先,我要定义UserBase
和User
类:
public class UserBase {
public string id;
}
public final class User extends UserBase {
public string name;
public List<UserBase> friends;
// user's "real" friends, not just ids, fills from SQLite
public List<User> userFriends;
}
正如您所看到的,friends
是Retrofit的UserBase
个对象列表,用于从JSON和userFriends
解析对象 - 列表,我们'将在后续步骤中手动填写SQLite。
现在,让我们定义一些与DB一起操作的帮助类:
public interface Dao<TItem> {
void add(List<TItem> items);
void removeAll();
List<TItem> getAll();
}
....
public abstract class AbstractDao<TItem> implements Dao<TItem> {
protected final SQLiteDatabase database;
protected final SqlUtilities sqlUtilities;
public AbstractDao(SQLiteDatabase database, SqlUtilities sqlUtilities) {
this.database = database;
this.sqlUtilities = sqlUtilities;
}
}
现在我们需要用于RelatedTable和UserTable的Dao:
public class UserRelation {
public String mainUserId;
public String relatedUserId;
}
...
public interface UserRelationDao extends Dao<UserRelation> {
...
List<User> getFriends(String userId);
...
}
...
public interface UserDao extends Dao<User> {
...
void addWithIgnore(List<TItem> items);
void update(List<TItem> items);
void upsert(List<TItem> items);
User getById(String userId);
...
}
一旦完成,我们实际上可以实现这个接口:
DefaultUserRelationDao
上课:
public class DefaultUserRelationDao extends AbstractDao<UserRelation> implements UserRelationDao {
static final String MAIN_USER_COLUMN = "mainuser";
static final String RELATED_USER_COLUMN = "relateduser";
private static final String[] COLUMN_NAMES = new String[]{
MAIN_USER_COLUMN,
RELATED_USER_COLUMN,
};
private static final String[] COLUMN_TYPES = new String[]{
"TEXT",
"TEXT",
};
private static final String TABLE = "userrelation";
static final String CREATE_TABLE = SqlUtilities.getCreateStatement(TABLE, COLUMN_NAMES, COLUMN_TYPES);
static final String ALL_CONNECTED_USERS =
"SELECT " + Joiner.on(",").join(DefaultUserDao.COLUMN_NAMES) +
" FROM " + UserTable.TABLE_NAME + "," + TABLE +
" WHERE " + RELATED_USER_COLUMN + "=" + DefaultUserDao.USER_ID_COLUMN;
public DefaultUserRelationDao(SQLiteDatabase database, SqlUtilities sqlUtilities) {
super(database, sqlUtilities);
}
@Override
public void add(List<UserRelation> userRelations) {
try {
database.beginTransaction();
ContentValues contentValues = new ContentValues();
for (UserRelation relation : userRelations) {
sqlUtilities.setValuesForUsersRelation(contentValues, relation);
database.insertOrThrow(TABLE, null, contentValues);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
@Override
public List<User> getFriends(String userId) {
Cursor cursor = database.rawQuery(ALL_CONNECTED_USERS, new String[]{userId});
return sqlUtilities.getConnectedUsers(cursor);
}
}
和DefaultUserDao
类:
public final class DefaultUserDao extends AbstractUDao<User> implements UserDao {
public static final String USER_ID_COLUMN = "userid";
static final String USER_NAME_COLUMN = "username";
public static final String[] COLUMN_NAMES = new String[]{
USER_ID_COLUMN,
USER_NAME_COLUMN,
};
private static final String TABLE = "users";
private static final String SELECT_BY_ID =
SqlUtilities.getSelectWhereStatement(TABLE, COLUMN_NAMES, new String[]{ USER_ID_COLUMN });
static final String CREATE_TABLE = SqlUtilities.getCreateStatement(TABLE, COLUMN_NAMES, COLUMN_TYPES);
public DefaultUserDao(SQLiteDatabase database, SqlUtilities sqlUtilities) {
super(database, sqlUtilities);
}
@Override
public void add(List<User> users) {
try {
database.beginTransaction();
ContentValues contentValues = new ContentValues();
for (User user : users) {
sqlUtilities.setValuesForUser(contentValues, user);
database.insertOrThrow(UserTable.TABLE_NAME, null, contentValues);
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
@Override
public User getById(String userId) {
return getUserBySingleColumn(SELECT_BY_ID, userId);
}
.....
private User getUserBySingleColumn(String selectStatement, String value) {
Cursor cursor = database.rawQuery(selectStatement, new String[]{value});
List<User> users = sqlUtilities.getUsers(cursor);
return (users.size() != 0) ? users.get(0) : null;
}
}
要创建我们的表,我们需要扩展SQLiteOpenHelper
并在onCreate()
实际创建表:
public final class DatabaseHelper extends SQLiteOpenHelper {
static final String DATABASE_NAME = "mysuper.db";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DefaultUserDao.CREATE_TABLE);
db.execSQL(DefaultUserRelationDao.CREATE_TABLE);
}
...
}
现在,我建议使用缓存定义LocalStorage接口以及所有可能的操作:
等
public interface LocalStorage {
User getUserById(String userId);
void addUsers(List<User> users);
....
}
它的实施:
public final class SqlLocalStorage implements LocalStorage {
private UserDao userDao;
private UserRelationDao userRelationDao;
private SQLiteDatabase database;
private final Object initializeLock = new Object();
private volatile boolean isInitialized = false;
private SqlUtilities sqlUtilities;
// there database is
// SQLiteOpenHelper helper = new DatabaseHelper(context);
// database = helper.getWritableDatabase();
public SqlLocalStorage(SQLiteDatabase database, SqlUtilities sqlUtilities) {
this.database = database;
this.sqlUtilities = sqlUtilities;
}
@Override
public User getUserById(String userId) {
initialize();
User user = userDao.getById(userId);
if (user == null) {
return null;
}
List<User> relatedUsers = userRelationDao.getFriends(userId);
user.userFriends = relaterUsers;
return user;
}
@Override
public void addUsers(List<User> users) {
initialize();
for (User user : users) {
for (UserBase friend : user) {
UserRelation userRelation = new UserRelation();
userRelation.mainUserId = user.id;
userRelation.relatedUserId = friend.id;
UserRelation userRelationMutual = new UserRelation();
userRelationMutual.mainUserId = friend.id;
userRelationMutual.relatedUserId = user.id;
userRelationDao.add(userRelation);
userRelationMutual.add(userRelation)
}
}
userDao.addWithIgnore(users);
}
void initialize() {
if (isInitialized) {
return;
}
synchronized (initializeLock) {
if (isInitialized) {
return;
}
Log.d(LOG_TAG, "Opens database");
userDao = new DefaultUserDao(database, sqlUtilities);
userRelationDao = new DefaultUserRelationDao(database, sqlUtilities);
isInitialized = true;
}
}
}
最后一步 - 它的实际用法:
//somewhere in non-UI thread
List<User> users = dataSource.getUsers();
localStorage.addUsers(users);
final User userBob = localStorage.getUserById("42");
NB!我在这里大量使用我的自定义类SqlUtilities。不幸的是,在这里发布它太大了,但只是一个例子来给出一些内在的想法 - 这里是getUsers(Cursor光标)看起来如何:
.....
public List<User> getUsers(Cursor cursor) {
ArrayList<User> users = new ArrayList<>();
try {
while (cursor.moveToNext()) {
users.add(getUser(cursor));
}
} finally {
cursor.close();
}
return users;
}
private User getUser(Cursor cursor) {
User user = new User(cursor.getString(0));
user.FullName = cursor.getString(1);
....
return user;
}
.....
我希望,你会原谅我跳过一些细节(特别是关于案例,当数据库必须更新时,当数据未满时除了从缓存中获取它之外,你必须检索它首先从服务器,然后加载到缓存等)。如果缺少任何关键部分 - 请在评论中发布,我很乐意更新帖子。
我希望,它会对你有帮助。
答案 1 :(得分:1)
您可以查看JSON-RPC。这是一个很好的框架,支持JSON解析和复杂对象关系的对象映射。
答案 2 :(得分:0)
我会说你正试图解决错误的问题&amp;真正的问题是你的数据表示被破坏了。除了循环引用问题之外,每个朋友都会为每个友谊复制它也效率低下。最好压扁你喜欢这样的人名单:
[
{
"id": "13",
"name": "Alice",
"friends": ["24"]
},
{
"id": "24",
"name": "Bob",
"friends": ["13"]
}
]
将列表存储在HashMap<Integer, Person>
(或SparseArray<Person>
)中。完成工作!