Java无法生成多个JSON文本

时间:2016-09-25 03:28:56

标签: java json

我正在尝试从我的数据中生成 json文件,但在我收到此异常之前,我最终只生成了一个json对象Java Cannot generate more than one JSON text

这是我的代码:

     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();
}

1 个答案:

答案 0 :(得分:0)

由于您似乎生成了多个对象,您确定不想生成对象数组吗?也许:

    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