【问题标题】:POJO representation from JSON来自 JSON 的 POJO 表示
【发布时间】:2017-04-12 13:08:06
【问题描述】:

首先请原谅我,因为我认为这是一个愚蠢的问题。我刚开始学习java

我有一个 json 文件,我将其解析为 POJO,以便对它们进行操作

这是解析器实现

public class ParsingTweet {

public static void main(String[] args) throws IOException {
    assert args != null & args.length > 0;
    List<Tweet> tweets = new ArrayList<>();
    ObjectMapper mapper = new ObjectMapper();
    try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) {
        String line;
        while ((line = reader.readLine()) != null) {
            tweets.add(mapper.readValue(line, Tweet.class));
        }
    }
    System.out.println(tweets);
 }
}

但是我的导师说这个结果不是真正的 POJO。它只是一个字符串表示。例如

[[text = I think this would be good. Would hopefully light the fire in the later rounds if you knew you were losing..., created_at = Mon Mar 06 22:48:07 +0000 2017, user = User@56f4468b, coordinates = null], [text = @Night_0f_Fire He's stuck in the alimony machine,, bust him out, created_at = Mon Mar 06 22:47:53 +0000 2017, user = User@6cc4c815, coordinates = null], ..., ..., ...]]]

那么实际的 POJO 是什么样子的?

PS。这是示例 json

{"text": "洪水/风暴/树倒塌。Northern Beaches (King Rd, Ingleside, NSW 2101) at 6 Mar 2017 21:38 , "user": {"id": "4721717942", "name ": "NSW Fire Updates"}, "lang": "en", "coordinates": { "coordinates": [151.264811, -33.6848] , "type":"Point"}, "created_at": "Mon Mar 06 10:44:31 +0000 2017"}, ..., ...

【问题讨论】:

  • 普通的旧 Java 对象。教练可能希望你做编组
  • 你假设每一行都是一个单独的json?这似乎很奇怪。但是,如果没问题,那么您的推文列表就没有问题,并且确实只包含简单的 java 结构对象。
  • 我逐行解析。我的讲师说所有 POJO 都存储在 List 推文中,但我也打印 System.out.println(tweets) 那么这怎么可能不是实际的 POJO?该任务只是解析。我实际上不必打印它,这不是必需的。但我只是好奇它实际上是什么样子
  • 您能否向我们展示文件的内容(可能只有几行)以了解您要解析的内容。
  • 确定我刚刚更新了它

标签: java json pojo


【解决方案1】:

以 Gson 为例。

String fullFile = ...read file...;
Gson gson = new Gson();
List<Tweet> tweets = gson.fromJson(fullFile, new TypeToken<ArrayList<Tweet>>(){});
System.out.println(tweets);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多