簡體   English   中英

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

[英]using Jackson API to parse JSON file in Java

我有以下JSON文件,並希望對其進行分析以創建tweet對象。

通過POJO類的定義,tweet對象應包含用戶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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM