Java JSON weird error - java

When I run my program I am getting the error:
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
at org.json.JSONObject.<init>(JSONObject.java:184)
at MovieLibrary.<init>(MovieLibrary.java:76)
at LibraryOfMovieDescriptions.main(LibraryOfMovieDescriptions.java:11)
Also, once I run the program, I check how my "movies2.json" has changed because that's the one I'm writing to to save the file, and it changes from initially only the file being { } to the file then being ’ t {}
I don't how I end up getting that in "movies2.json".
"movies.json", the file being used in the MovieLibrary constructor is this:
{ "Minions Puppy": {
"Released": "10 Dec 2013",
"Rated": "NR",
"Actors": ["Dave", "Gru"],
"Plot": "Dave seeing many owners walk their dogs wants a puppy of his own. He finds a mini-UFO who becomes his pal. This short film released with Despicable Me 2 chronicles how Dave helps the UFO return home.",
"Runtime": "4:16 min",
"Genre": ["Animation", "Family", "Cartoon"],
"Filename": "MinionsPuppy.mp4",
"Title": "Minions Puppy"
},
"Pretty Woman": {
"Released": "10 Dec 1973",
"Rated": "NR",
"Actors": ["Roy Orbison"],
"Plot": "One of Roys most famous songs.",
"Runtime": "3 min",
"Genre": ["Country Music"],
"Filename": "RoyOrbisonPrettyWoman.mp4",
"Title": "Pretty Woman"
},
"Minions Banana Song": {
"Released": "12 Dec 2015",
"Rated": "PG",
"Actors": ["Steve", "Kevin", "Bob", "Stuart"],
"Plot": "Banana is a song sung by The Minions in the teaser trailer of Despicable Me 2. It is a parody of the Beach Boys Barbara Ann. One minion gets annoyed by another, most likely Stuart, who keeps on playing his party horn while they are singing. So, at the end, he punched Stuart.",
"Runtime": "5 min",
"Genre": ["Animation", "Family", "Cartoon"],
"Filename": "MinionsBananaSong.mp4",
"Title": "Minions Banana Song"
},
"Minions Banana": {
"Released": "12 Dec 2015",
"Rated": "PG",
"Actors": ["Steve", "Kevin", "Stuart"],
"Plot": "Minions fight over a banana. In the process, they wreak havoc in the Bomb Factory.",
"Runtime": "5 min",
"Genre": ["Animation", "Family", "Cartoon"],
"Filename": "MinionsBanana.mp4",
"Title": "Minions Banana"
},
"Squatters Rights": {
"Released": "07 Jun 1946",
"Rated": "N/A",
"Actors": ["Dessie Flynn", "James MacDonald"],
"Plot": "Chip-n-Dale have set up house in the wood stove of Mickeys cabin. Pluto knows they are there, but Mickey only knows his matches keep going out when he tries to light a fire.",
"Runtime": "7 min",
"Genre": ["Cartoon", "Animation", "Family"],
"Filename": "MMSquattersRights.mp4",
"Title": "Squatters Rights"
}
}
So I would really love any help or explanation. Thanks in advance.
Here is the code:
MAIN CLASS
import java.io.Serializable;
class LibraryOfMovieDescriptions implements Serializable {
public static void main(String[] args){
MovieLibrary movieLibrary;
movieLibrary = new MovieLibrary("movies.json");
movieLibrary.toJsonFile("movies2.json");
}
}
MovieDescription Class
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.io.Serializable;
public class MovieDescription implements Serializable {
private String title;
private String rating;
private String release;
private String runtime;
private String plot;
private String filename;
private String genre;
private String actors;
public JSONObject toJSONObject() throws JSONException {
JSONObject obj = new JSONObject();
obj.put("Title", title);
obj.put("Rated", rating);
obj.put("Released", release);
obj.put("Runtime", runtime);
obj.put("Plot", plot);
obj.put("Filename", filename);
JSONArray a = new JSONArray();
String[] sArray = this.actors.split(" , ");
for(int i = 0; i < sArray.length; i++){
a.put(i);
}
obj.put("Actors", a);
JSONArray g = new JSONArray();
String[] gArray = this.genre.split(" , ");
for(int i = 0; i < gArray.length; i++){
g.put(i);
}
obj.put("Genre", g);
return obj;
}
public MovieDescription(JSONObject jsonObj) throws JSONException{
this.title = jsonObj.getString("Title");
this.rating = jsonObj.getString("Rated");
this.release = jsonObj.getString("Released");
this.plot = jsonObj.getString("Plot");
this.runtime = jsonObj.getString("Runtime");
this.filename = jsonObj.getString("Filename");
JSONArray g = jsonObj.getJSONArray("Genre");
for(int i = 0; i < g.length(); i++){
this.genre += g.get(i) + ", ";
}
JSONArray a = jsonObj.getJSONArray("Actors");
for(int i = 0; i < a.length(); i++){
this.actors += a.get(i) + ", ";
}
}
public MovieDescription(){
title = " ";
rating = " ";
release = " ";
runtime = " ";
plot = " ";
filename = " ";
genre = " ";
actors = " ";
}
public MovieDescription(String title, String rating, String release, String runtime, String plot, String filename,
String genre, String actors){
this.title = title;
this.rating = rating;
this.release = release;
this.runtime = runtime;
this.plot = plot;
this.filename = filename;
this.genre = genre;
this.actors = actors;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return title;
}
public void setRating(String rating){
this.rating = rating;
}
public String getRating(){
return rating;
}
public void setRelease(String release){
this.release = release;
}
public String getRelease(){
return this.release;
}
public void setRuntime(String runtime){
this.runtime = runtime;
}
public String getRuntime(){
return runtime;
}
public void setPlot(String plot){
this.plot = plot;
}
public String getPlot(){
return plot;
}
public void setFilename(String filename){
this.filename = filename;
}
public String getFilename(){
return filename;
}
public void setGenre(String genre){
this.genre = genre;
}
public String getGenre(){
return genre;
}
public void setActors(String actors){
this.actors = actors;
}
public String getActors(){
return actors;
}
public String toString(){
String string = ("Title: " + title + "\n" + "Rating: " + rating + "\n" + "Released: " + release + "\n" +
"Runtime: " + runtime + "\n" + "Plot: " + plot + "\n" + "Filename: " + filename + "\n" + "Genre: " + genre
+ "\n" + "Actors: " + actors + "\n");
return string;
}
}
MovieLibrary Class
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.json.JSONTokener;
import java.io.Serializable;
import java.io.ObjectOutputStream;
public class MovieLibrary implements Serializable {
private List<MovieDescription> movieLib = new ArrayList<MovieDescription>();
private int arraySize;
public MovieLibrary(){
arraySize = 0;
}
public boolean isEmpty(){
return arraySize == 0;
}
public MovieDescription get(String aTitle){
int i = indexOf(aTitle);
if(i == -1){
return null;
}
return movieLib.get(i);
}
public boolean add(MovieDescription aClip){
movieLib.add(aClip);
arraySize++;
return true;
}
public boolean remove(String aTitle){
int i = indexOf(aTitle);
if(i != -1){
movieLib.remove(i);
arraySize--;
}
return true;
}
public String[] getTitles(){
String[] s = new String[movieLib.size()];
for(int i = 0; i < movieLib.size(); i++){
s[i] = movieLib.get(i).getTitle();
}
return s;
}
private int indexOf(String aTitle){
for(int i = 0; i < movieLib.size(); i++)
if(((movieLib.get(i)).getTitle()).equals(aTitle)){
return i;
}
return -1;
}
public MovieLibrary(String jsonFile){
FileInputStream in = null;
JSONObject jsonObj = null;
String[] titles;
try{
in = new FileInputStream(jsonFile);
jsonObj = new JSONObject(new JSONTokener(in));
titles = JSONObject.getNames(jsonObj);
System.out.println("Adding Movies...");
for(int i = 0; i < titles.length; i++){
System.out.println(titles[i]);
JSONObject temp = jsonObj.getJSONObject(titles[i]);
MovieDescription movies = new MovieDescription(temp);
movieLib.add(movies);
}
System.out.println(movieLib);
in.close();
}
catch(Exception e){
e.printStackTrace();
if(in != null){
try{
in.close();
}
catch(IOException z){
z.printStackTrace();
System.exit(0);
}
}
}
}
public void toJsonFile(String jsonFileName){
JSONObject jsonObj = new JSONObject();
ObjectOutputStream out = null;
try{
for(int i = 0; i < movieLib.size(); i++)
jsonObj.put(movieLib.get(i).getTitle(),movieLib.get(i).toJSONObject());
out = new ObjectOutputStream(new FileOutputStream(jsonFileName));
out.writeObject(jsonObj.toString());
out.close();
}
catch(Exception e){
e.printStackTrace();
if(out != null){
try{
out.close();
}
catch(IOException z){
z.printStackTrace();
System.exit(0);
}
}
}
}
}

You don't want to use an ObjectOutputStream to write text. It's writing a serialized Java string and that explains the weird characters at the start of your file. Try using a FileWriter instead.
public void toJsonFile(String jsonFileName) {
JSONObject jsonObj = new JSONObject();
FileWriter out = null;
try{
for(int i = 0; i < movieLib.size(); i++)
jsonObj.put(movieLib.get(i).getTitle(),movieLib.get(i).toJSONObject());
out = new FileWriter(jsonFileName);
out.write(jsonObj.toString());
out.close();
}
catch(Exception e){
e.printStackTrace();
if(out != null){
try{
out.close();
}
catch(IOException z){
z.printStackTrace();
System.exit(0);
}
}
}
}
P.S. You might also change your try/catch block to a try-with-resources statement.

Related

How to parsing multi dimensional json data array in android studio.? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
i have problem to parse my json data,
this is my json data :
{"data":
[
{"ean": "222222","itemname": "","location": "001010202,001010201","po":[
{"ponumber": 1,"qty": 22
},
{"ponumber": 2,"qty": 33
}
]
},
{
"ean": "11112222",
"itemname": "เหงือก",
"location": "001010601",
"po": [
{
"ponumber": 1,
"qty": 7
}
]
},
{
"ean": "22223333",
"itemname": "Crystal Water",
"location": "001010410,001010401",
"po": [
{
"ponumber": 3,
"qty": 13
}
]
}
]}
i want to show the output like :
thank you
this is my java code to parsing json data and show to listview :
void parseJsonData(String jsonString) throws JSONException {
String data = "";
String data2 = null;
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname +"\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++ ) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2 = "\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n";
list.add(data+data2);
System.err.println(data+data2);
}
}
ArrayAdapter<String> LVarray;
LVarray = new ArrayAdapter<String>(ListActivity.this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(LVarray);
}
this is screen shot the output:
1.You can use StringBuilder to save the data2(po List).
2.In the inner for loop ,you can use append method to add it in it .
3.Get the length of StringBuilder .Then remove the saved data2.
4.Then you can save again .
Edit
public void parseJsonData(String jsonString) throws JSONException {
String data = "";
StringBuilder data2 = new StringBuilder();
List<String> list = new ArrayList<>();
JSONObject json = new JSONObject(jsonString);
JSONArray arrayData = json.getJSONArray("data");
for (int i = 0; i < arrayData.length(); i++) {
JSONObject jsonDataArray = arrayData.getJSONObject(i);
String ean = jsonDataArray.getString("ean");
String itemname = jsonDataArray.getString("itemname");
String locations = jsonDataArray.getString("location");
data = "\n EAN = " + ean +
"\n Item Name = " + itemname + "\n";
JSONArray arrayPO = jsonDataArray.getJSONArray("po");
for (int j = 0; j < arrayPO.length(); j++) {
JSONObject jsonPO = arrayPO.getJSONObject(j);
ponumb = jsonPO.getString("ponumber");
qty = jsonPO.getString("qty");
//int numb = i + 1;
data2.append("\n PO Number : " + ponumb +
"\n Quantity : " + qty + "\n");
list.add(data + data2);
}
System.err.println(data + data2);
int sb_length = data2.length();
data2.delete(0, sb_length);
}
}
this also can help
try {
//Get root array
JSONArray data_array = jsonObject.getJSONArray("data");
for (int i=0;i<data_array.length();i++){
JSONObject jsonObject1 = array.getJSONObject(i);
String ean = jsonObject1.optString("ean");
String itemname = jsonObject1.optString("itemname");
String location = jsonObject1.optString("location");
JSONArray child_Array = jsonObject1.getJSONArray("po");
for (int j=0;j<childArray.length();j++){
JSONObject childJosnObject = array.getJSONObject(i);
String ponumber = jsonObject1.optString("ponumber");
String qty = jsonObject1.optString("qty");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You have to try like this, it will help you
JsonParseModel jsonParseModel = new Gson().fromJson(jsonString,JsonParseModel.class);
public class JsonParseModel {
private ArrayList<DataClass> data;
public ArrayList<DataClass> getData() {
return data;
}
public void setData(ArrayList<DataClass> data) {
this.data = data;
}
public class DataClass{
private String ean,itemname,location;
private ArrayList<PoData> po;
public String getEan() {
return ean;
}
public void setEan(String ean) {
this.ean = ean;
}
public String getItemname() {
return itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public ArrayList<PoData> getPo() {
return po;
}
public void setPo(ArrayList<PoData> po) {
this.po = po;
}
public class PoData{
private int ponumber,qty;
public int getPonumber() {
return ponumber;
}
public void setPonumber(int ponumber) {
this.ponumber = ponumber;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
}
}
private void parseJsondata(String response) {
try {
// response
JSONObject jsonObject = new JSONObject(response);
// get data from JSONArray
JSONArray data = jsonObject.getJSONArray("data");
// for loop to your JSONArray's Strings
for (int i = 0; i < data.length(); i++) {
// get JSONObject from i
JSONObject jo = data.getJSONObject(i);
// get string
String ean = jo.getString("ean");
String itemname = jo.getString("itemname");
String location = jo.getString("location");
JSONArray jA = jo.getJSONArray("po");
for (int j = 0; j < jA.length(); j++) {
// get JSONObject by jO
JSONObject jO = jA.getJSONObject(i);
// get string
String ponumber = jO.getString("ponumber");
String qty = jO.getString("qty");
}
}
//Log response
Log.e("response:", response);
} catch (JSONException e) {
e.printStackTrace();
}
}

JSON error when writing to

I am trying to run my code and I keep getting error. The json file I'm reading in is completely fine with the keys and values. And the one I am trying to write out is just a json file with "{ }" and that's it. Please help me. It's the only error I'm getting.
MAIN CLASS
import java.io.Serializable;
class LibraryOfMovieDescriptions implements Serializable {
public static void main(String[] args){
MovieLibrary movieLibrary;
movieLibrary = new MovieLibrary("movies.json");
movieLibrary.toJsonFile("movies2.json");
}
}
MovieDescription Class
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.io.Serializable;
public class MovieDescription implements Serializable {
private String title;
private String rating;
private String release;
private String runtime;
private String plot;
private String filename;
private String genre;
private String actors;
public JSONObject toJSONObject() throws JSONException {
JSONObject obj = new JSONObject();
obj.put("Title", title);
obj.put("Rated", rating);
obj.put("Released", release);
obj.put("Runtime", runtime);
obj.put("Plot", plot);
obj.put("Filename", filename);
JSONArray a = new JSONArray();
String[] sArray = this.actors.split(" , ");
for(int i = 0; i < sArray.length; i++){
a.put(i);
}
obj.put("Actors", a);
JSONArray g = new JSONArray();
String[] gArray = this.genre.split(" , ");
for(int i = 0; i < gArray.length; i++){
g.put(i);
}
obj.put("Genre", g);
return obj;
}
public MovieDescription(JSONObject jsonObj) throws JSONException{
this.title = jsonObj.getString("Title");
this.rating = jsonObj.getString("Rated");
this.release = jsonObj.getString("Released");
this.plot = jsonObj.getString("Plot");
this.runtime = jsonObj.getString("Runtime");
this.filename = jsonObj.getString("Filename");
JSONArray g = jsonObj.getJSONArray("Genre");
for(int i = 0; i < g.length(); i++){
this.genre += g.get(i) + ", ";
}
JSONArray a = jsonObj.getJSONArray("Actors");
for(int i = 0; i < a.length(); i++){
this.actors += a.get(i) + ", ";
}
}
public MovieDescription(){
title = " ";
rating = " ";
release = " ";
runtime = " ";
plot = " ";
filename = " ";
genre = " ";
actors = " ";
}
public MovieDescription(String title, String rating, String release, String runtime, String plot, String filename,
String genre, String actors){
this.title = title;
this.rating = rating;
this.release = release;
this.runtime = runtime;
this.plot = plot;
this.filename = filename;
this.genre = genre;
this.actors = actors;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return title;
}
public void setRating(String rating){
this.rating = rating;
}
public String getRating(){
return rating;
}
public void setRelease(String release){
this.release = release;
}
public String getRelease(){
return this.release;
}
public void setRuntime(String runtime){
this.runtime = runtime;
}
public String getRuntime(){
return runtime;
}
public void setPlot(String plot){
this.plot = plot;
}
public String getPlot(){
return plot;
}
public void setFilename(String filename){
this.filename = filename;
}
public String getFilename(){
return filename;
}
public void setGenre(String genre){
this.genre = genre;
}
public String getGenre(){
return genre;
}
public void setActors(String actors){
this.actors = actors;
}
public String getActors(){
return actors;
}
public String toString(){
String string = ("Title: " + title + "\n" + "Rating: " + rating + "\n" + "Released: " + release + "\n" +
"Runtime: " + runtime + "\n" + "Plot: " + plot + "\n" + "Filename: " + filename + "\n" + "Genre: " + genre
+ "\n" + "Actors: " + actors + "\n");
return string;
}
}
MovieLibrary Class
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.json.JSONTokener;
import java.io.Serializable;
import java.io.ObjectOutputStream;
public class MovieLibrary implements Serializable {
private List<MovieDescription> movieLib = new ArrayList<MovieDescription>();
private int arraySize;
public MovieLibrary(){
arraySize = 0;
}
public boolean isEmpty(){
return arraySize == 0;
}
public MovieDescription get(String aTitle){
int i = indexOf(aTitle);
if(i == -1){
return null;
}
return movieLib.get(i);
}
public boolean add(MovieDescription aClip){
movieLib.add(aClip);
arraySize++;
return true;
}
public boolean remove(String aTitle){
int i = indexOf(aTitle);
if(i != -1){
movieLib.remove(i);
arraySize--;
}
return true;
}
public String[] getTitles(){
String[] s = new String[movieLib.size()];
for(int i = 0; i < movieLib.size(); i++){
s[i] = movieLib.get(i).getTitle();
}
return s;
}
private int indexOf(String aTitle){
for(int i = 0; i < movieLib.size(); i++)
if(((movieLib.get(i)).getTitle()).equals(aTitle)){
return i;
}
return -1;
}
public MovieLibrary(String jsonFile){
FileInputStream in = null;
JSONObject jsonObj = null;
String[] titles;
try{
in = new FileInputStream(jsonFile);
jsonObj = new JSONObject(new JSONTokener(in));
titles = JSONObject.getNames(jsonObj);
System.out.println("Adding Movies...");
for(int i = 0; i < titles.length; i++){
JSONObject temp = jsonObj.getJSONObject(titles[i]);
MovieDescription movies = new MovieDescription(temp);
movieLib.add(movies);
}
System.out.println(this.getTitles());
in.close();
}
catch(Exception e){
e.printStackTrace();
if(in != null){
try{
in.close();
}
catch(IOException z){
z.printStackTrace();
System.exit(0);;
}
}
}
}
public void toJsonFile(String jsonFileName){
JSONObject jsonObj = new JSONObject();
ObjectOutputStream out = null;
try{
for(int i = 0; i < movieLib.size(); i++)
jsonObj.put(movieLib.get(i).getTitle(),movieLib.get(i).toJSONObject());
out = new ObjectOutputStream(new FileOutputStream(jsonFileName));
out.writeObject(jsonObj.toString());
out.close();
}
catch(Exception e){
e.printStackTrace();
if(out != null){
try{
out.close();
}
catch(IOException z){
z.printStackTrace();
System.exit(0);
}
}
}
}
}
And here is the error I am getting:
Adding Movies...
[Ljava.lang.String;#4554617c
Also, after I run the program and check my "movies2.json" (the one I'm trying to write to) the file turns to this.
weird stuff:
The first message is because System.out.println is passed an array of strings (this.getTitles()). To display this array of string, one must convert it to a single string Arrays.toString(this.getTitles()), or use a for loop iterating on the array to display one title per line.
The wrong output is because ObjectOutputStream is an output stream for serializing Java objects (even though in this case it is a String object) in binary. FileWriter should be a better option to consider, as its API allows you to write characters to a file.

Get data from file - Buffered Reader

I would just have the id, the content and the hashtag and time of every tweet in a text file, and I dont know how to store infomration in lists of tweet,
I created a tweet class as follows:
public class Tweet {
private String type;
private String origin;
private String tweetText;
private String url;
private String tweetID;
private String tweetDate;
private int retCount;
private String favourit;
private String mEntities;
private String hashtags;
public Tweet(String tweetID,String origin) {
this.tweetID = tweetID;
this.origin = origin;
}
public Tweet(String type, String origin, String tweetText, String url, String tweetID, String tweetDate, int retCount, String favourit, String mEntities, String hashtags) {
this.type = type;
this.origin = origin;
this.tweetText = tweetText;
this.url = url;
this.tweetID = tweetID;
this.tweetDate = tweetDate;
this.retCount = retCount;
this.favourit = favourit;
this.mEntities = mEntities;
this.hashtags = hashtags;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getOrigin() {
return origin;
}
public void setOrigin(String origin) {
this.origin = origin;
}
public String getTweetText() {
return tweetText;
}
public void setTweetText(String tweetText) {
this.tweetText = tweetText;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTweetID() {
return tweetID;
}
public void setTweetID(String tweetID) {
this.tweetID = tweetID;
}
public String getTweetDate() {
return tweetDate;
}
public void setTweetDate(String tweetDate) {
this.tweetDate = tweetDate;
}
public int getRetCount() {
return retCount;
}
public void setRetCount(int retCount) {
this.retCount = retCount;
}
public String getFavourit() {
return favourit;
}
public void setFavourit(String favourit) {
this.favourit = favourit;
}
public String getmEntities() {
return mEntities;
}
public void setmEntities(String mEntities) {
this.mEntities = mEntities;
}
public String getHashtags() {
return hashtags;
}
public void setHashtags(String hashtags) {
this.hashtags = hashtags;
}
and my data file has the following format:
***
***
Type:status
Origin: Here's link to listen live to our discussion of #debtceiling #politics :
Text: Here's link to listen live to our discussion of :
URL:
ID: 96944336150867968
Time: Fri Jul 29 09:05:05 CDT 2011
RetCount: 0
Favorite: false
MentionedEntities:
Hashtags: debtceiling politics
***
***
Type:status
Origin: Now we're talking #debtceiling w/ Dick Polman #NewsWorksWHYY #PhillyInquirer & Bill Galston #BrookingsInst #NoLabelsOrg
Text: Now we're talking w/ Dick Polman & Bill Galston
URL:
ID: 96943803600089088
Time: Fri Jul 29 09:02:58 CDT 2011
RetCount: 1
Favorite: false
MentionedEntities: 136337303 151106990 14495726 15161791
Hashtags: debtceiling
***
***
I want to read this file and stock information into lists, i begin with this code, but i dont know how to solve that
public static List<String> readTweets(File file) throws IOException {
List<String> tweets = new ArrayList<String>();
//logger.info("Read tweets from {}", file.getAbsolutePath());
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
String[] fields;
while ((line = reader.readLine()) != null) {
fields = line.split(",");
if (fields.length > 1)
tweets.add(fields[1]);
}
return tweets;
}
By the looks of the code you are experimenting with, this is what I would do:
public static List<String> readTweets(File file) throws IOException {
List<String> tweets = new ArrayList<String>();
List<String> lines = Files.readAllLines(file.toPath());
for(int i = 0; i < lines.length(); i++){
String line = lines.get(i);
String[] part = line.split(",");
if(part.length < 1) tweets.add(part[i]);
}
}
But, if I wrote an application that was purely for printing the contents of tweets into the console, here's how I'd do it:
TweetReader.java
package Testers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
public class TweetReader {
public static List<Tweet> readTweets(File file) throws IOException {
boolean processEnd = false;
String type = "";
String origin = "";
String tweetText = "";
String url = "";
String tweetID = "";
String tweetDate = "";
int retCount = 0;
String favourite = "";
String mEntities = "";
String hashTags = "";
List<Tweet> tweets = new ArrayList<Tweet>();
List<String> lines = Files.readAllLines(file.toPath());
for(int i = 0; i < lines.size(); i++){
String line = lines.get(i);
line = line.trim();
if(line.equals("***")){
if(processEnd){
Tweet tweet = new Tweet(type, origin, tweetText, url, tweetID, tweetDate, retCount, favourite, mEntities, hashTags);
tweets.add(tweet);
processEnd = false;
}else processEnd = true;
}else{
if(line.contains(":")){
String header = line.substring(0, line.indexOf(":"));
//System.out.println(header); //You can uncomment this for troubleshooting
if(header.equals("Type")) type = line.substring(line.length() > 5 ? 5 : line.length());
else if(header.equals("Origin")) origin = line.substring(line.length() > 8 ? 8 : line.length());
else if(header.equals("Text")) tweetText = line.substring(line.length() > 6 ? 6 : line.length());
else if(header.equals("URL")) url = line.substring(line.length() > 5 ? 5 : line.length());
else if(header.equals("ID")) tweetID = line.substring(line.length() > 4 ? 4 : line.length());
else if(header.equals("Time")) tweetDate = line.substring(line.length() > 6 ? 6 : line.length());
else if(header.equals("RetCount")) retCount = Integer.parseInt(line.substring(line.length() > 10 ? 10 : line.length()));
else if(header.equals("Favorite")) favourite = line.substring(line.length() > 11 ? 11 : line.length());
else if(header.equals("MentionedEntities")) mEntities = line.substring(line.length() > 19 ? 19 : line.length());
else if(header.equals("Hashtags")) hashTags = line.substring(line.length() > 10 ? 10 : line.length());
else throw new IOException("Line cannot be identified as part of a tweet:" + line);
}else throw new IOException("Line cannot be processed:" + line);
}
}
return tweets;
}
public static void main(String[] args){
File log = new File("log.txt");
List<Tweet> tweets = new ArrayList<Tweet>();
try {
File f = new File(".").getAbsoluteFile();
File[] array = f.listFiles();
for(int i = 0; i < array.length; i++){
File tweet = array[i];
if(tweet.isFile() && !tweet.getName().contains("log.txt") && !tweet.getName().contains(".jar")){
log("Reading file: " + tweet.getAbsolutePath(), log);
List<Tweet> tweetlist = readTweets(tweet);
tweets.addAll(tweetlist);
}
}
System.out.println("Reading tweets now");
for(int i = 0; i < tweets.size(); i++){
Tweet t = tweets.get(i);
log("Type = " + t.getType(), log);
log("Origin = " + t.getOrigin(), log);
log("Text = " + t.getTweetText(), log);
log("URL = " + t.getURL(), log);
log("ID = " + t.getTweetID(), log);
log("Date = " + t.getTweetDate(), log);
log("Ret count = " + t.getRetCount(), log);
log("Favourite = " + t.getFavourite(), log);
log("Mentioned entities = " + t.getMentionedEntities(), log);
log("Hashtags = " + t.getHashtags(), log);
log("Tweet finished", log);
}
} catch (IOException e) {
log(e, log);
}
log("Finished reading tweets.", log);
}
private static void log(IOException e, File log) {
log(e.getMessage(), log);
StackTraceElement[] array = e.getStackTrace();
for(int i = 0; i < array.length; i++){
log(" " + array[i], log);
}
}
private static void log(String string, File log) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(log, true));
writer.write(string);
writer.newLine();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Tweet.java
package Testers;
public class Tweet {
private String type;
private String origin;
private String tweetText;
private String url;
private String tweetID;
private String tweetDate;
private int retCount;
private String favourit;
private String mEntities;
private String hashtags;
public Tweet(String tweetID,String origin) {
this.tweetID = tweetID;
this.origin = origin;
}
public Tweet(String type, String origin, String tweetText, String url, String tweetID, String tweetDate, int retCount, String favourit, String mEntities, String hashtags) {
this.type = type;
this.origin = origin;
this.tweetText = tweetText;
this.url = url;
this.tweetID = tweetID;
this.tweetDate = tweetDate;
this.retCount = retCount;
this.favourit = favourit;
this.mEntities = mEntities;
this.hashtags = hashtags;
}
public String getType() {
return type;
}
public String getOrigin(){
return origin;
}
public String getTweetText(){
return tweetText;
}
public String getURL(){
return url;
}
public String getTweetID(){
return tweetID;
}
public String getTweetDate(){
return tweetDate;
}
public int getRetCount(){
return retCount;
}
public String getFavourite(){
return favourit;
}
public String getMentionedEntities(){
return mEntities;
}
public String getHashtags(){
return hashtags;
}
}
//global attribute
List<Tweet> tweetList = new ArrayList<>();
String line = "";
String[] fields;
while (line != null) {
line = reader.readLine();
line = reader.readLine();
//these two are for ***
for(int i = 0;i<10;i++){
line = reader.readLine();
tweets.add(line);
// these are for the other data
}
Tweet tweet = createTweetFromList(tweets);
tweetList.add(tweet);
}

Reading textfile with multiple elements into arraylist (set and get)

I am trying to read from a text file of the type (Artist, Title, Genre, Recordcompany, Release year, Number of songs, Playtime):
The Beatles, Abbey Road, Rock, Apple Records, 1969, 17, 47.16
Sia, 1000 Forms of Fear, Pop, Intertia, 2014, 12, 48.41
Taylor Swift, Speak Now
I have created a CD class:
package q;
public class CD {
//
private String artist;
private String titel;
private String genre;
private String recordcompany;
private int year; //
private int songs; //
private double playtime; //
public CD() { //
}
public CD(String newArtist, String newTitel) {
artist = newArtist;
titel = newTitel;
}
public CD(String newArtist, String newTitel, String newGenre, String newRecordcompany, int newYear, int newSongs, double newPlaytime) {
artist = newArtist;
titel = newTitel;
genre = newGenre;
recordcompany = newRecordcompany;
year = newYear;
songs = newSongs;
playtime = newPlaytime;
}
public String getArtist() { //
return artist;
}
public String getTitel() {
return titel;
}
public String getGenre() {
return genre;
}
public String getRecordcompany() {
return recordcompany;
}
public int getYear() {
return year;
}
public int getsong() {
return songs;
}
public double getPlaytime() {
return playtime;
}
public void setArtist(String newArtist) { //
artist = newArtist;
}
public void setTitel(String newTitel) {
titel = newTitel;
}
public void setGenre(String newGenre) {
genre = newGenre;
}
public void setRecordcompany(String newRecordcompany) {
recordcompany = newRecordcompany;
}
public void setYear(int newYear) {
year = newYear;
}
public void setSongs(int newSongs) {
songs = newSongs;
}
public void setplaytime(double newPlaytime) {
playtime = newPlaytime;
}
#
Override public String toString() { //
return ("Artist " + artist + System.lineSeparator() + "Titel: " + titel + System.lineSeparator() + "Genre: " + genre + System.lineSeparator() + "Recordcompany: " + recordcompany + System.lineSeparator() + "Year: " + year + System.lineSeparator() + "Songs: " + songs + System.lineSeparator() + "Playtime: " + playtime + System.lineSeparator());
}
}
I am trying to read from the text file and then convert it into a arraylist. I know I have overcomplicated it by first conerting the text file to a string array and then converting it to an arraylist. I would like to use set and get methods when I create the array, if it is possible. I wonder if any of you have any tips for me for how I can make the code less complicated and include set and get methods if possible, thank you.
package q;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class Q {
public static void main(String[] args) throws FileNotFoundException {
String artist = "";
String titel = "";
String genre = "";
String recordcompany = "";
String year = "";
String songs = "";
String playtime = "";
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String tmp[] = line.split(",");
artist = tmp[0];
titel = tmp[1];
if (tmp.length > 2) {
genre = tmp[2];
recordcompany = tmp[3];
year = (tmp[4]);
songs = (tmp[5]);
playtime = (tmp[6]);
} else {
genre = "";
recordcompany = "";
year = "";
songs = "";
playtime = "";
}
List < String > unsorted = Arrays.asList(tmp);
for (String e: unsorted) {
System.out.println(e);
}
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
EDITED
package q;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Q {
public static void main(String[] args) throws FileNotFoundException {
String artist = "";
String titel = "";
String genre = "";
String recordcompany = "";
int year = 0;
int songs = 0;
double playtime = 0.0;
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
List < CD > cdsList = new ArrayList < > ();
while ((line = br.readLine()) != null) {
CD cd = new CD();
String tmp[] = line.split(",");
cd.setArtist(tmp[0]);
cd.setTitel(tmp[1]);
if (tmp.length > 2) {
cd.setGenre(tmp[2]);
cd.setRecordcompany(tmp[3]);
cd.setYear(Integer.parseInt(tmp[4].trim()));
cd.setSongs(Integer.parseInt(tmp[5].trim()));
cd.setplaytime(Double.parseDouble(tmp[6].trim()));
}
System.out.println(cdsList);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
Something like below.
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader("nej.txt"));
String line = null;
List < CD > cdsList = new ArrayList < > ();
while ((line = br.readLine()) != null) {
CD cd = new CD();
String tmp[] = line.split(",");
cd.setArtist(tmp[0]);
cd.setTitel(tmp[1]);
if (tmp.length > 2) {
cd.setGenre(tmp[2]);
cd.setRecordcompany(tmp[3]);
cd.setYear(Integer.parseInt(tmp[4].trim()));
cd.setSongs(Integer.parseInt(tmp[5].trim()));
cd.setplaytime(Double.parseDouble(tmp[6].trim()));
}
cdsList.add(cd);
}
System.out.println(cdsList);
br.close();
} catch (IOException e) {
System.out.println(e);
}
}

JSON Object should not add if it is repeated

Scanner input = new Scanner(System.in);
JSONArray finaljson = new JSONArray();
for (int j = 0; j < 2; j++) {
System.out.println("Enter Version Name");
String vName = input.next();
System.out.println("Enter Version Key");
;
String vKey = input.next();
JSONObject root = new JSONObject();
if (!root.has("versionName")) {
root.put("versionName", vName);
root.put("versionKey", vKey);
}
JSONArray issue = new JSONArray();
System.out.println("Enter Epic Name");
String epicName = input.next();
System.out.println("Enter Epic Key");
String epicKey = input.next();
JSONObject epicData = new JSONObject();
epicData.put("epickKey", epicKey);
epicData.put("epickName", epicName);
issue.put(epicData);
root.put("issue", issue);
finaljson.put(root);
}
System.out.println("JSON DATA" + finaljson.toString());
Hey Making a JSON,as from the code if user will enter versionname is multiple time that it should not add in root jsonobject. so how to restrict it.
[
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e1",
"epickKey": "ekey1"
}
],
"versionName": "v1"
},
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e2",
"epickKey": "eky2"
}
],
"versionName": "v1"
}
]
but want
[
{
"versionKey": "vkey1",
"issue": [
{
"epickName": "e1",
"epickKey": "eky1"
},
{
"epickName": "e2",
"epickKey": "eky2"
}
],
"versionName": "v1"
}
]
can you help me how to make this type of dynamic json data
If I understand correctly, you want the output to be like the second JSON array in your question. Changing where you loop should do the trick:
Scanner input = new Scanner(System.in);
JSONArray finaljson = new JSONArray();
System.out.println("Enter Version Name");
String vName = input.next();
System.out.println("Enter Version Key");;
String vKey = input.next();
JSONObject root = new JSONObject();
if (!root.has("versionName")) {
root.put("versionName", vName);
root.put("versionKey", vKey);
}
JSONArray issue = new JSONArray();
for (int j = 0; j < 2; j++) {
System.out.println("Enter Epic Name");
String epicName = input.next();
System.out.println("Enter Epic Key");
String epicKey = input.next();
JSONObject epicData = new JSONObject();
epicData.put("epickKey", epicKey);
epicData.put("epickName", epicName);
issue.put(epicData);
}
root.put("issue", issue);
finaljson.put(root);
System.out.println("JSON DATA" + finaljson.toString());
I tested with the input you have. Here is the formatted JSON output:
[
{
"issue": [
{
"epickKey": "eky1",
"epickName": "e1"
},
{
"epickKey": "eky2",
"epickName": "e2"
}
],
"versionName": "vkey1",
"versionKey": "v1"
}
]
Read in your json using Gson:
Define Pojos for your Json Objects:
public class Epic {
String versionKey, versionName;
Issue issue;
}
public class Issue{
String epicName, epicKey;
}
Load Pojos from json using Gson
// Create gson object
Gson gson = new GsonBuilder().create();
// Load your json objects:
BufferedReader br = new BufferedReader(new FileReader("file.json"));
List<Epic> epics = gson.fromJson(br, new TypeToken<ArrayList<Epic>>() {}.getType());
Create the class structure you want for your "multi-issue-epics":
// This will be used to store in the format you want
public class MultiIssueEpic{
public String versionKey, versionName;
public Set<Issue> issueSet;
public MultiIssueEpic(Epic epic){
this.versionName = epic.versionName;
this.versionKey = epic.versionKey;
this.issueSet = new HashSet<>();
this.issueSet.add(epic.issue);
}
}
Build the MultiIssueEpic up from your List<Epic>:
Map<String, MultiIssueEpic> epicMap = new HashMap<>();
for(Epic epic : epics){
if(epicMap.contains(epic.versionName)){
// Add issue to existing MultiIssueEpic
epicMap.get(epic.versionName).issueSet.add(epic.issue);
} else{
// Add new MultiIssueEpic
epicMap.put(epic.versionName, new MultiIssueEpic(epic));
}
}
// Here is your list of MultiIssueEpics:
List<MultiIssueEpic> multiIssueEpics = new ArrayList<>(epicMap.values());
I change your code and I add two other class. One named Data for (versionKey, nameKey), the second one Epic for (epickName,epickKey)
and to generate Json, I use Gson lib.
This code :
Epic Class:
public class Epic {
private String epicName;
private String epicKey;
public Epic() {
}
public Epic(String epicName, String epicKey) {
this.epicName = epicName;
this.epicKey = epicKey;
}
public String getEpicName() {
return epicName;
}
public void setEpicName(String epicName) {
this.epicName = epicName;
}
public String getEpicKey() {
return epicKey;
}
public void setEpicKey(String epicKey) {
this.epicKey = epicKey;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Epic [epicName=");
builder.append(epicName);
builder.append(", epicKey=");
builder.append(epicKey);
builder.append("]");
return builder.toString();
}
}
Data Class :
import java.util.List;
public class Data {
private String versionName;
private String versionKey;
private List<Epic> epics;
public Data() {
}
public Data(String versionName, String versionKey, List<Epic> epics) {
this.versionName = versionName;
this.versionKey = versionKey;
this.epics = epics;
}
public String getVersionName() {
return versionName;
}
public void setVersionName(String versionName) {
this.versionName = versionName;
}
public String getVersionKey() {
return versionKey;
}
public void setVersionKey(String versionKey) {
this.versionKey = versionKey;
}
public List<Epic> getEpics() {
return epics;
}
public void setEpics(List<Epic> epics) {
this.epics = epics;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((versionKey == null) ? 0 : versionKey.hashCode());
result = prime * result
+ ((versionName == null) ? 0 : versionName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Data other = (Data) obj;
if (versionKey == null) {
if (other.versionKey != null)
return false;
} else if (!versionKey.equals(other.versionKey))
return false;
if (versionName == null) {
if (other.versionName != null)
return false;
} else if (!versionName.equals(other.versionName))
return false;
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Data [versionName=");
builder.append(versionName);
builder.append(", versionKey=");
builder.append(versionKey);
builder.append(", epics=");
builder.append(epics);
builder.append("]");
return builder.toString();
}
}
Main Class:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Data> datas = new ArrayList<Data>();
boolean add = false;
for (int j = 0; j < 2; j++) {
add = false;
Data data = new Data();
System.out.println("Enter Version Name");
data.setVersionName(input.next());
System.out.println("Enter Version Key");
data.setVersionKey(input.next());
Epic epic = new Epic();
System.out.println("Enter Epic Name");
epic.setEpicName(input.next());
System.out.println("Enter Epic Key");
epic.setEpicKey(input.next());
List<Epic> epics = new ArrayList<Epic>();
if(datas.isEmpty()){
epics.add(epic);
data.setEpics(epics);
datas.add(data);
}else{
for(Data d:datas){
if(d.equals(data)){
d.getEpics().add(epic);
add=true;
}
}
if(!add){
epics.add(epic);
data.setEpics(epics);
datas.add(data);
}
}
}
//Gson gson = new GsonBuilder().setPrettyPrinting().create();
//System.out.println(gson.toJson(datas));
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(datas);
System.out.println(jsonArray.toString());
}
}
PS: Url to download Gson API
Edit
I made a change in the Main Class to use json-lib-2.4-jdk15.jar
Take a look at this URL:
json-lib

Categories

Resources