2

我正在尝试解析从对 Facebook 的请求中提供的提要。但是,我的解析器跳过了很多信息。下面是代码的一部分,一个正在解析的内容以及 if 语句中打印的内容的示例。例如,从未找到“消息”。想法?

List<FacebookItem> list = new ArrayList<FacebookItem>();

try {
    if (jFactory == null)
        jFactory = new JsonFactory();

    jParser = jFactory.createJsonParser(json);

    FacebookItem o = null;
    while (jParser.nextToken() != null) {
        if ("type".equals(jParser.getCurrentName())) {
            jParser.nextToken();
            o = new FacebookItem();
            o.setType(jParser.getText());
            System.out.println("Found type:   " + jParser.getText());
        }
        if ("from".equals(jParser.getCurrentName()))
            while (!"name".equals(jParser.getCurrentName())) {
                jParser.nextToken();
            }
            jParser.nextToken();
            o.getUser().setUserName(jParser.getText());
            System.out.println("Found name:   " + jParser.getText());
        }
        if ("message".equals(jParser.getCurrentName())) {
            jParser.nextToken();
            o.setText(jParser.getText());
            System.out.println("Found message:   " + jParser.getText());
        }
        if ("created_time".equals(jParser.getCurrentName())) {
            jParser.nextToken();
            o.setTimestamp(jParser.getText());
            System.out.println("Found created_time:   " + jParser.getText());
            list.add(o);
        }
    }
    jParser.close();

} catch (JsonGenerationException e) {
    e.printStackTrace();
} catch (JsonMappingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

{"data":[{"type":"photo","link":"http://www.facebook.com/photo.php?fbid=10151331660204305&set=a.299455459304.180838.197394889304&type=1&relevant_count=1"," from":{"name":"FC Barcelona","category":"职业运动队","id":"197394889304"},"message":"普约尔面临八周裁员 http://bit.ly/ QXhOFE\r\n\r\nPuyol, vuit setmanes de baixa http://bit.ly/T1enma\r\n\r\nPuyol, ocho semanas de baja http://bit.ly/T0eaj8","图片" :"http://photos-g.ak.fbcdn.net/hphotos-ak-snc6/246623_10151331660204305_75156416_s.jpg","created_time":"2012-10-03T17:40:06+0000","id":" 197394889304_10151331937599305"},{"type":"checkin",“链接”:“http://www.facebook.com/pages/Hubben-21/249474758405147”,“来自”:{“名称”:“Andreas Rol\u00e9n”,“id”:“575703056”}, message":"En timme in i turneringen och redan chipleader","picture":"http://profile.ak.fbcdn.net/static-ak/rsrc.php/v2/y5/r/j258ei8TIHu.png", "name":"Hubben 2.1","created_time":"2012-10-03T17:24:19+0000","id":"575703056_10151181582028057"},{"type":"photo","link":" http://www.facebook.com/photo.php?fbid=10151445544542786&set=at.10151445533587786.588547.694032785.688088336&type=1&relevant_count=1","from":{"name":"Jens Wilhelmsson","id":"688088336 "},"图片":"http://photos-h.ak.fbcdn.net/hphotos-ak-prn1/72091_10151445544542786_676020840_s.jpg","created_time":"2012-10-03T17:21:40+0000","id" :"688088336_10151111148358337"},{"type":"link","from":{"name":"Eric Lindqvist","id":"648057222"},"created_time":"2012-10-03T17:20 :52+0000","id":"648057222_10151249963167223"}created_time":"2012-10-03T17:20:52+0000","id":"648057222_10151249963167223"}created_time":"2012-10-03T17:20:52+0000","id":"648057222_10151249963167223"}

Found type:   photo
Found name:   FC Barcelona
Found name:   Andreas Rolén
Found name:   Hubben 2.1
Found created_time:   2012-10-03T17:24:19+0000
Found type:   photo
Found name:   Jens Wilhelmsson
Found name:   Eric Lindqvist
4

3 回答 3

1

我真的不知道你的 JSON 库,但是 Android在 SDK 本身中提供了一个很好的 JSON API,为什么不使用它呢?

JSONArray data = new JSONArray(jsonString);
int itemCount = data.length();
List<MyObject> list = new ArrayList<MyObject>(itemCount);

for (int i=0; i<itemCount; ++i) {
  JSONObject item = data.getJSONObject(i);

  String name = item.getString("name");
  String message = item.optString("message");

  MyObject o = new MyObject(name, message);
  list.add(o);
}

最好的办法甚至是将单个项目的 JSON 解析封装到 MyObject 类中:

JSONArray data = new JSONArray(jsonString);
int itemCount = data.length();
List<MyObject> list = new ArrayList<MyObject>(itemCount);

for (int i=0; i<itemCount; ++i) {
  JSONObject item = data.getJSONObject(i);

  MyObject o = new MyObject();
  o.setFromJSON(item);
  list.add(o);
}
于 2012-10-03T20:14:51.857 回答
1

我真的很喜欢Jackson,它速度很快,而且非常有能力。我从未使用过流 API(您在此处使用的),但它确实看起来很困难。除非您非常关心内存使用情况,否则我建议您不要使用流式 API。由于您使用的是移动设备,因此显然更关心资源,所以这就是您的决定。

如果您决定放弃流式 API,最简单的方法是创建一个映射到 JSON 的 java 对象模型,然后使用 ObjectMapper 将字符串读入该对象模型。您可以使用注释自定义转换,以重命名映射或其他的字段。像下面这样的东西应该可以工作(取决于 FacebookItem 的真正定义。)

  import org.codehaus.jackson.map.DeserializationConfig.Feature;
  ....
  ObjectMapper mapper = new ObjectMapper();
  // tell it to not fail on properties that you don't have mapped, that way you
  // only have to map the fields you are interested in and can ignore the rest
  mapper.getDeserializationConfig().set(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  ItemContainer itemContainer = mapper.readValue(facebookDataJsonString, ItemContainer.class);

  // where elsewhere you have defined something like:

  class ItemContainer {
    List<FacebookItem> data;
    // getters and setters for data.
  }

以下是 eugen 在评论中指定的选项。如果您的 JSON 包含一个列表,这将起作用(即没有“数据”包装器,而是看起来像[{...},{...}]

  ObjectMapper mapper = new ObjectMapper();
  // tell it to not fail on properties that you don't have mapped, that way you
  // only have to map the fields you are interested in and can ignore the rest
  mapper.getDeserializationConfig().set(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  List<FacebookItem> items = mapper.readValue(jsonString, new TypeReference<List<Stuff>>(){});

最后,第三种选择是如果您没有对象映射,则仅将其读入 Map。那么至少你不必处理 JSONObject 和 JSONArray 的东西。

  ObjectMapper mapper = new ObjectMapper();
  Map<String, Object> container = mapper.readValue(facebookDataJsonString, Map.class);
  List<Map<String,Object>> = container.get("data");
  for (Map<String,Object> map : container ) {
    System.out.println( "type is " + map.get("type"));
    System.out.println( "from is " + ((Map<String,Object>)map.get("from")).get("name"));
    System.out.println( "message is " + map.get("message"));
  }
于 2012-10-03T20:24:43.783 回答
-1

首先 - JSON 字符串不完整 - 最后缺少 ]}。当我附加它时,我的 costom 构建的 JSON 解析器得到以下结果:

  data:
    id=197394889304_10151331937599305
    picture=http://photos-g.ak.fbcdn.net/hphotos-ak-snc6/246623_10151331660204305_75156416_s.jpg
    message=Puyol faces eight week layoff http://bit.ly/QXhOFE\r\n\r\nPuyol, vuit setmanes de baixa http://bit.ly/T1enma\r\n\r\nPuyol, ocho semanas de baja http://bit.ly/T0eaj8
    link=http://www.facebook.com/photo.php?fbid=10151331660204305&set=a.299455459304.180838.197394889304&type=1&relevant_count=1
    from:
      id=197394889304
      category=Professional sports team
      name=FC Barcelona
    created_time=2012-10-03T17:40:06+0000
    type=photo
    id=575703056_10151181582028057
    picture=http://profile.ak.fbcdn.net/static-ak/rsrc.php/v2/y5/r/j258ei8TIHu.png
    message=En timme in i turneringen och redan chipleader
    name=Hubben 2.1
    link=http://www.facebook.com/pages/Hubben-21/249474758405147
    from:
      id=575703056
      name=Andreas Rol\u00e9n
    created_time=2012-10-03T17:24:19+0000
    type=checkin
    id=688088336_10151111148358337
    picture=http://photos-h.ak.fbcdn.net/hphotos-ak-prn1/72091_10151445544542786_676020840_s.jpg
    link=http://www.facebook.com/photo.php?fbid=10151445544542786&set=at.10151445533587786.588547.694032785.688088336&type=1&relevant_count=1
    from:
      id=688088336
      name=Jens Wilhelmsson
    created_time=2012-10-03T17:21:40+0000
    type=photo
    id=648057222_10151249963167223
    from:
      id=648057222
      name=Eric Lindqvist
    created_time=2012-10-03T17:20:52+0000
    type=link

我现在的问题 - 这里一切都好吗?有什么错误吗?

于 2013-09-06T21:06:22.717 回答