简体   繁体   English

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

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

I have the following JSON file and wish to parse it to create tweet objects. 我有以下JSON文件,并希望对其进行分析以创建tweet对象。

the tweet objects should contain user id, username, text, coordinates, and timestamp through the definition of POJO class. 通过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"}

this is what i did 这就是我所做的

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

Jackson is pretty straight forward. 杰克逊挺直的。 Create your .java classes with user id, username, text, coordinates, and timestamp. 使用用户ID,用户名,文本,坐标和时间戳创建您的.java类。 You can make them all string variables (makes it super easy to map). 您可以使它们成为所有字符串变量(使其超级容易映射)。 You can always parse out later once the data is mapped 映射数据后,您以后随时可以解析

ParsedTweets.class: ParsedTweets.class:

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

Implementation: 实现方式:

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

To read from file you do: 要从文件读取,请执行以下操作:

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