marsupials
marsupials

Reputation: 81

parsing JSON array of objects with gson

I'm trying to use gson to parse a JSON file containing an array of objects. I'm getting a "Exception in thread "main" com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 2" error on this line of code:

  RecipeList[] myRecipe = gson.fromJson(theLine, RecipeList[].class);

I am a bit confused about using gson so I don't think I've set things up properly. The data is in this format:

[  {
"id": 10259,
"cuisine": "greek",
"ingredients": [
  "romaine lettuce",
  "black olives"
]  }, {
"id": 25693,
"cuisine": "southern_us",
"ingredients": [
  "plain flour",
  "ground pepper",
  "salt",
  "tomatoes",
  "ground black pepper",
  "thyme"
]  }]

the code trying to read that is:

inputStream = new FileReader("filepath\\file.json");
BufferedReader myReader = new BufferedReader(inputStream);
theLine = myReader.readLine();

Gson gson = new Gson();
RecipeList[] myRecipe = gson.fromJson(theLine, RecipeList[].class);

my RecipeList class, which was intended to store the array of recipe objects in the json file (but I think this must be wrong)

ArrayList<Recipe> recipeArray;

public RecipeList (Recipe recipObj){
    recipeArray.add(recipObj);
}

And my Recipe class, for the creation of each recipe object in the json array:

String recipeID;
String cuisine;
ArrayList<String> ingredients;


public Recipe (String id, String cuisine, ArrayList<String> ingredients){
    this.recipeID = id;
    this.cuisine = cuisine;
    for (int k = 0; k < ingredients.size(); k++){
        this.ingredients.add(ingredients.get(k));
    }
}  

I appreciate any help. I'm a bit confused over the reading of the json text using gson and how to create the individual objects from that array.

thanks Rebecca

Upvotes: 0

Views: 1371

Answers (1)

Haider Ali
Haider Ali

Reputation: 342

theLine = myReader.readLine();

you need to read all lines from file until eof.

ex:

    br = new BufferedReader(new FileReader("C:\\testing.txt"));

String line="";
                while ((line = br.readLine()) != null) {
                    theLine+=line;
                }

Upvotes: 1

Related Questions