到目前爲止,我有一個tweet.json文件,裏面是tweet的集合。我已經構建了一個tweet.class,它是tweet中鍵值的對象集合。使用Jackson的解析器實現
現在我想實現一個使用jackson的解析,它應該在tweet.json中逐行運行,並且每條推文(行)被解析爲POJO。因此,每一行是一個單一的POJO
如何做到這一點
這是我做了什麼
ObjectMapper mapper = new ObjectMapper();
ParsedTweets tweets = mapper.readValue(new File("tweet.json"), tweet.class);
例如JSON文件
{"text": "MVA/Transport. Greater Hume (Hume Hwy, Holbrook, NSW 2644) at 7 Mar 2017 03:58 #NSWRFS #MVATransport", "user": {"id": "4721717942", "name": "NSW Fire Updates"}, "lang": "en", "coordinates": { "coordinates": [147.273696, -35.785469] , "type":"Point"}, "created_at": "Mon Mar 06 17:29:31 +0000 2017"}
{"text": "Yes! Everything happens for a reason. The rain doesn't want the Swedru people to go& flood Westhills mall this evening", "user": {"id": "724288148", "name": "Pyper Pebbles"}, "lang": "en","created_at": "Mon Mar 06 17:19:49 +0000 2017"}
{"text": "5 Sure-Fire Ways That Can Help You Achieve Better Success In Life , "user": {"id": "41049329", "name": "StarCentral Magazine"}, "lang": "en","created_at": "Mon Mar 06 17:08:36 +0000 2017"}
tweet.class
的public class Tweet {
private String text;
private String created_at;
private User user;
private Coordinates coordinates;
public Tweet(){
}
public String getText()
{
return text;
}
public void setText(String text)
{
this.text = text;
}
public String getCreated_at()
{
return created_at;
}
public void setCreated_at(String created_at)
{
this.created_at = created_at;
}
public User getUser()
{
return user;
}
public void setUser(User user)
{
this.user = user;
}
public Coordinates getCoordinates()
{
return coordinates;
}
public void setCoordinates(Coordinates coordinates)
{
this.coordinates = coordinates;
}
@Override
public String toString()
{
return "ClassPojo [text = "+text+", created_at = "+created_at+", user = "+user+", coordinates = "+coordinates+"]";
}
}
更新ReadWriteJson實施
public class ReadWriteJson {
public static void main(String[] args) throws IOException {
assert args != null & args.length > 0;
List<Tweet> tweet = new ArrayList<>();
ObjectMapper mapper = new ObjectMapper();
try (BufferedReader reader = new BufferedReader(new FileReader("tweets.json"))) {
String line;
while ((line = reader.readLine()) != null){
tweet.add(mapper.readValue(line, Tweet.class));
}
}
}
您可以加入json'的'一個例子以及Tweet'類的'結構 –
當然,我只是說 – Kutam