Hana :
I ultimately want to create inverted indexes using my JSON dataset. I know how to parse through one JSON object but how can I iterate through many? Here is what I have working:
File1:
{
"doc_id": "2324jos",
"screen_name": "twitter_user101",
"tweet_text": "Its a beautiful day to be productive",
"hashtags": "[]",
"links": "[]",
"place_type": "city",
"place_name": "Evergreen Park",
"created_at": "2019-02-08 22:24:03"
}
My code:
public class ParseJson {
public static void main(String[] args) throws Exception {
// this is the key object to convert JSON to Java
Tweet tweet;
ObjectMapper mapper = new ObjectMapper();
try {
File json = new File("test.json");
tweet = mapper.readValue(json, Tweet.class);
System.out.println("Java object created from JSON String :");
System.out.println(tweet);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public class Tweet {
public String doc_id;
public String screen_name;
public String tweet_text;
public String hashtags;
public String links;
public String place_type;
public String place_name;
public String created_at;
public Tweet() {
}
public Tweet(String doc_id, String screen_name, String tweet_text, String hashtags, String links, String place_type, String place_name, String created_at) {
this.doc_id = doc_id;
this.screen_name = screen_name;
this.tweet_text = tweet_text;
this.hashtags = hashtags;
this.links = links;
this.place_name = place_name;
this.place_type = place_type;
this.created_at = created_at;
}
@Override
public String toString() {
return doc_id + screen_name + tweet_text;
}
}
Now, I want to iterate through this JSON file which has 2 JSON objects in an array:
File2:
[
{
"doc_id": "2324jos",
"screen_name": "b'LIBBYRULZ'",
"tweet_text": "@ABC ya'll be lying",
"hashtags": "[]",
"links": "[]",
"place_type": "city",
"place_name": "Evergreen Park",
"created_at": "2019-02-08 22:24:03"
},
{
"doc_id": "8982hol",
"screen_name": "b'eddylee_1'",
"tweet_text": "Hungry for money",
"hashtags": "[]",
"links": "[]",
"place_type": "city",
"place_name": "Manhattan",
"created_at": "2/7/2019 17:01"
}
]
How can I adjust my above code using Jackson to do so where the doc_id is the unique key? I want to be able to return all the data in each JSON object for each doc_id.
Matt :
To parse an array of JSON objects using Jackson:
Tweet[] tweets = mapper.readValue(json, Tweet[].class);
should do the trick. See below:
public class ParseJson {
public static void main(String[] args) throws Exception {
Tweet[] tweets;
ObjectMapper mapper = new ObjectMapper();
try {
File json = new File("test.json");
tweets = mapper.readValue(json, Tweet[].class);
System.out.println("Java object created from JSON String :");
Arrays.asList(tweets).forEach(System.out::println); // Prints each element in the array
} catch (IOException ex) {
ex.printStackTrace();
}
}
}