【问题标题】:Storing JSON document with AppEngine使用 AppEngine 存储 JSON 文档
【发布时间】:2016-06-02 14:06:19
【问题描述】:

我正在尝试使用 Objectify 作为持久层将 JSON 文档存储到 AppEngine 数据存储中。为了能够查询文档值,而不是将整个文档插入为 String 字段,我创建了一个 MapEntity,如下所示:

@Entity(name="Map") 
public class MapEntity {
    @Id
    private Long id;
    private Map<String,String> field;
        // Code omitted 
}

因为最终“展开”时 JSON 文档中的每个键值都可以用 Map 表示

例子:

    String           subText          = "{\"first\": 111, \"second\": [2, 2, 2], \"third\": 333}";
    String           jsonText         = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789, \"fourth\":"
                                        + subText + "}";

我会将地图字段存储在数据存储中:

KEY              VALUE
field.first  => 123
field.second => [4,5,6]
field.third  => 789
field.fourth-first => 111
field.fourth-second => [2,2,2]
field.fourth-third => 333

如果我使用我的parse() 方法:

使用 JSON.Simple 库解析 JSON 文档,然后进行递归解析:

private MapEntity parse(String root, MapEntity entity, Map json) {
    Iterator iter = json.entrySet().iterator();
    while (iter.hasNext()) {
         Map.Entry entry = (Map.Entry) iter.next();
         if (entry.getValue() instanceof Map){
             entity = parse((String)entry.getKey()+"-", entity, (Map) entry.getValue());
             System.out.println("Map instance");
         } else {
             entity.setField(root + String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));  
         }
    }
    return entity;
}

我的应用是这样工作的:

 MapEntity jsonEntity = new MapEntity();
 Map json = null;
 json = (Map) parser.parse(jsonText, containerFactory); // JSON.Simple parser
 jsonEntity = parse("", jsonEntity, json);

我遇到的问题是:

  • 我不能使用“.” Map 键字段中的点,所以我必须使用“-”
  • 另外,我存储 JSON 文档的方法效率不高

【问题讨论】:

    标签: google-app-engine objectify json-simple


    【解决方案1】:

    如果您的 JSON 遵循严格的格式,您最好构建一个类来表示您的数据格式,并使用像 Jackson 这样的库直接在该类之间进行序列化。您可以将该类直接用作 Objectify 中的实体类,但是否要这样做取决于您是否要:

    • 存储和公开完全相同的数据集
    • 将存储和 JSON 表示紧密结合

    【讨论】:

      【解决方案2】:

      您可以使用 JSONObject 作为 MapEntity 的替代品,并使用 toString() 方法将 json 作为字符串存储到谷歌应用引擎。检索后,您可以使用适当的构造函数简单地恢复 JSONObject。当然,这会限制您在应用引擎中为属性编制索引并对其进行查询的能力。

      如果您希望 Objectify 为您执行此操作,您可以注册一个 Translator 来负责调用 toString() 和重建。

      【讨论】:

      • JSONObject 的链接断开
      • @coto 损坏的链接已修复。
      猜你喜欢
      • 1970-01-01
      • 2019-01-31
      • 2012-05-28
      • 2015-02-14
      • 2017-06-30
      • 1970-01-01
      • 2010-11-12
      • 2013-06-29
      • 2014-04-12
      相关资源
      最近更新 更多