Fawaz Al-Turbaq Fawaz Al-Turbaq - 2 months ago 10
Java Question

Java Cannot generate more than one JSON text

I'm trying to generate a json file from my data but I end up generating only one json object before I get this exception "Java Cannot generate more than one JSON text"

This is my code:

OutputStream fos = new FileOutputStream("new_fake_students.json",false);
JsonGenerator g = Json.createGenerator(fos);
while (matcher.find())
{
String temp = matcher.group();
String[] values = temp.split(",");
if(values.length>=4)
{
g.writeStartObject();
g.write("id",values[0]);
g.write("name",values[1]+values[2]);
g.write("major",values[3]);
g.writeEnd();
}
}
g.close();
fos.close();
}

Answer

As it seems that you generate more than one object, are you sure you don't want to generate an array of objects? Perhaps:

    OutputStream fos = new FileOutputStream("new_fake_students.json",false);
    JsonGenerator g = Json.createGenerator(fos);
    g.writeStartArray(); // start the array
    while (matcher.find())
    {
        String temp = matcher.group();
        String[] values = temp.split(",");
        if(values.length>=4)
        { 
          g.writeStartObject();
          g.write("id",values[0]);
          g.write("name",values[1]+values[2]);
          g.write("major",values[3]);
          g.writeEndObject(); // does g.writeEnd() even exists?
        }
    }
    g.writeEndArray(); // close that array
Comments