have a structure for a contact book:
Contact { "Name":{ "First name":"Erm","Last Name": "Smith" }, "Number":67485647 }.
I save it as a Json object and than store it in a file with createContact().
public synchronized void createContact (String fname, String lname,String typeof, int number) throws FileNotFoundException
{
JsonObjectBuilder contactBuilder = Json.createObjectBuilder();
JsonObjectBuilder nameBuilder = Json.createObjectBuilder();
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
nameBuilder.add("First Name",fname);
nameBuilder.add("Last Name",lname);
contactBuilder.add("Name", nameBuilder);
contactBuilder.add("Type", typeof);
contactBuilder.add("number", number);
JsonObject contact = contactBuilder.build();
contactArrayBuilder.add(contact);
JsonArray contactArray=contactArrayBuilder.build();
//write to file
OutputStream os = new FileOutputStream(filename);
JsonWriter fileWriter = Json.createWriter(os);
fileWriter.writeArray(contactArray);
fileWriter.close();
}
I read the file with:
InputStream is = new FileInputStream(filename);
JsonReader fileReader = Json.createReader(is);
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readObject());
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
This is when I get the error
javax.json.JsonException: Cannot read JSON object, found JSON array
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:105)
I am using javax.json