使用 Jackson API 解析 Java 中的 JSON 文件



我有以下JSON文件,并希望解析它以创建推文对象。

推文对象应通过 POJO 类的定义包含用户 ID、用户名、文本、坐标和时间戳

{"text": "I think this would be good. Would hopefully light the fire in the later rounds if you knew you were losing", "user": {"id": "39455201", "name": "Elvis Sinosic"}, "lang": "en","created_at": "Mon Mar 06 22:48:07 +0000 2017"}
{"text": "@Night_0f_Fire He's stuck in the alimony machine,, bust him out", "user": {"id": "2744192965", "name": "Mitch L"}, "lang": "en","created_at": "Mon Mar 06 22:47:53 +0000 2017"}

这就是我所做的

import com.fasterxml.jackson.databind.*;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Tweets {
    private long userID;
    private String userName;
    private String text;
    private List<int> coordinates;
    private String timestamp;
}
ObjectMapper mapper = new ObjectMapper();
ObjectMapper mapper = new ObjectMapper();
Tweets tweets = mapper.readValue(new("/Users/YusufNing/IdeaProjects/comp6700-2017/ass1/parsing/Tweets.java"), Tweets.class);

克逊非常简单。使用用户 ID、用户名、文本、坐标和时间戳创建.java类。你可以把它们都变成字符串变量(使映射变得非常容易(。映射数据后,您始终可以稍后解析

ParsedTweets.class:

public class ParsedTweets
{
    private String id;
    private String username;
    private String text; 
    private String coordinates;
    private String timestamp;
}

实现:

ObjectMapper mapper = new ObjectMapper();
String jsonTweeterString = "{'text': 'I think this would be good. Would hopefully light the fire in the later rounds if you knew you were losing', 'user': {'id': '39455201', 'name': 'Elvis Sinosic'}, 'lang': 'en','created_at': 'Mon Mar 06 22:48:07 +0000 2017'}";
ParsedTweets tweets = mapper.readValue(jsonTweeterString, ParsedTweets.class);

要从文件中读取,请执行以下操作:

ParsedTweets tweets = mapper.readValue(new File("/Users/Kutam/IdeaProjects/comp6700-2017/ass1/tweets.js‌​on"), ParsedTweets.class);

最新更新