有联系簿的结构:
Contact { "Name":{ "First name":"Erm","Last Name": "Smith" }, "Number":67485647 }.
我将其保存为Json对象,而不是将其存储在带有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();
}
我用以下文件阅读了文件:
InputStream is = new FileInputStream(filename);
JsonReader fileReader = Json.createReader(is);
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readObject());
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
这是我收到错误的时候
javax.json.JsonException: Cannot read JSON object, found JSON array
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:105)
我正在使用javax.json
答案 0 :(得分:1)
问题是您在该文件中存储JsonArray,然后尝试将JsonArray作为JsonObject读取。您可以采取哪些措施来解决这些问题:
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readArray());
JsonArrayBuilder contactArrayBuilder= Json.createArrayBuilder();
并用以下内容替换它们:
JsonArray array = fileReader.readArray();
最后,阅读文件将如下所示:
InputStream is = new FileInputStream(filename);
JsonReader fileReader = Json.createReader(is);
JsonArray array = fileReader.readArray();
答案 1 :(得分:0)
更改此行
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readObject());
到这个
JsonArray contactObj = (JsonArray) Json.createParserFactory(fileReader.readArray());
因为您期待一个数组,但是读取该对象时会出现此错误。