如何将 json 字符串中的多条记录插入到 java 中的 google 数据存储中
how to insert multiple records from json string into google datastore in java
每当我收到 json 字符串作为请求时,我必须将其插入数据存储 entities.Following 是读取 json 字符串并存储到实体中的示例代码。
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Key abckey = KeyFactory.createKey("aaa","aaa1");
Entity abcentity = new Entity(abckey);
JSONArray abc;
Iterator iter = abc.iterator();
while (iter.hasNext()) {
innerObj = (JSONObject) iter.next();
abcentity.setProperty("id",Integer.parseInt(innerObj.get(
"id").toString()));
abcentity.setProperty("mid", Integer.parseInt(innerObj
.get("mid").toString()));
abcentity.setProperty("status", 1);
abcentity.setProperty("tid", touserid);
ds.put(abcentity);
}
只要有记录就在迭代json数组。但是在 google 管理控制台中,它只显示最后一条记录。这是将多条记录插入数据存储区的正确方法吗?如果没有,请给我一些解决方案。
因为你只创建了一次
试试这个:
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
JSONArray abc;
Iterator iter = abc.iterator();
while (iter.hasNext()) {
innerObj = (JSONObject) iter.next();
// create
Key abckey = KeyFactory.createKey("aaa",Long.parseLong(innerObj.get(
"id").toString()));
Entity abcentity = new Entity(abckey);
// fill with data
// ...
// abcentity.setProperty ...
//
// save
ds.put(abcentity);
}
Key
是您实体的标识符,而不是名为 id
的字段
每当我收到 json 字符串作为请求时,我必须将其插入数据存储 entities.Following 是读取 json 字符串并存储到实体中的示例代码。
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Key abckey = KeyFactory.createKey("aaa","aaa1");
Entity abcentity = new Entity(abckey);
JSONArray abc;
Iterator iter = abc.iterator();
while (iter.hasNext()) {
innerObj = (JSONObject) iter.next();
abcentity.setProperty("id",Integer.parseInt(innerObj.get(
"id").toString()));
abcentity.setProperty("mid", Integer.parseInt(innerObj
.get("mid").toString()));
abcentity.setProperty("status", 1);
abcentity.setProperty("tid", touserid);
ds.put(abcentity);
}
只要有记录就在迭代json数组。但是在 google 管理控制台中,它只显示最后一条记录。这是将多条记录插入数据存储区的正确方法吗?如果没有,请给我一些解决方案。
因为你只创建了一次
试试这个:
DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
JSONArray abc;
Iterator iter = abc.iterator();
while (iter.hasNext()) {
innerObj = (JSONObject) iter.next();
// create
Key abckey = KeyFactory.createKey("aaa",Long.parseLong(innerObj.get(
"id").toString()));
Entity abcentity = new Entity(abckey);
// fill with data
// ...
// abcentity.setProperty ...
//
// save
ds.put(abcentity);
}
Key
是您实体的标识符,而不是名为 id