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

时间:2017-04-10 19:21:24

标签: java json twitter jackson

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

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

{"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);

1 个答案:

答案 0 :(得分:4)

杰克逊很直接。使用用户标识,用户名,文本,坐标和时间戳创建.java类。您可以将它们全部变为字符串变量(使其非常容易映射)。您可以随后在映射数据后解析

ParsedTweets.class:

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);

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

func *<T1:Sequence, T2:Sequence>(lhs: T1,rhs : T2) ->     
          LazySequence<FlattenSequence<LazyMapSequence<T1,
          LazyMapSequence<T2, (T1.Iterator.Element, T2.Iterator.Element)>>>> {
    let product =  lhs.lazy.flatMap({ x in rhs.lazy.map{y in (x,y)}})
    print(type(of:product))
    return product
}