我尝试使用beanIo到json解析一个固定长度的平面文件
代码:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;
import org.beanio.BeanIOConfigurationException;
import org.beanio.BeanReader;
import org.beanio.StreamFactory;
import org.junit.Test;
import com.google.gson.Gson;
public class EmployeeBeanIOHandlerTest {
@Test
public void testHandleEmployee() {
// mapping pattern file
String mappingPatternFile = "pattern-mapping.xml";
// data file (csv)
String objectFile = "employee.csv";
// stream name defined in pattern mapping file
String streamName = "empData";
Gson gson = new Gson();
BeanReader beanReader = null;
Reader reader = null;
StreamFactory factory = null;
InputStream in = null;
try {
System.out.println("## RESULT FOR " + objectFile + " ##");
// create a StreamFactory
factory = StreamFactory.newInstance();
// load the setting file
in = this.getClass().getClassLoader()
.getResourceAsStream(mappingPatternFile);
// get input stream reader of object file (data file)
reader = new InputStreamReader(this.getClass().getClassLoader()
.getResourceAsStream(objectFile));
// load input stream to stream factory
factory.load(in);
beanReader = factory.createReader(streamName, reader);
Map<?, ?> record = null;
while ((record = (Map<?, ?>) beanReader.read()) != null) {
System.out.println(beanReader.getRecordName() + ": "
+ gson.toJson(record));
}
} catch (BeanIOConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
if (beanReader != null) {
beanReader.close();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
但是我看到的输出:
header: {"id":"Header","date":"01012013"}
emp: {"lastName":"Lilik","title":"Senior Developer","hireDate":"Oct 1, 2009
12:00:00 AM","salary":7500000,"firstName":"Robertus"}
emp: {"lastName":"Doe","title":"Architect","hireDate":"Jan 15, 2008 12:00:00 AM","salary":8000000,"firstName":"Jane"}
emp: {"lastName":"Anderson","title":"Manager","hireDate":"Mar 18, 2006 12:00:00 AM","salary":9000000,"firstName":"Jon"}
trailer: {"id":"Trailer","count":"3"}
它为找到的每个记录生成单独的json对象。
参考部位:http://www.sourcefreak.com/2013/06/painless-flat-file-parsing-with-beanio/
以下是我的要求:
1.我想要一个统一的Json文件。
1.在重复记录的情况下,它应该形成一个json数组。
如果你能帮忙我会很感激的。
2条答案
按热度按时间4szc88ey1#
此答案基于OP提供的链接中找到的数据和
pattern-mapping.xml
文件。数据:
顶盖,01012013
Robertus,Lilik,高级开发人员,“75,000,00”,10012009
Jane,Doe,建筑师,“80,000,00”,01152008
Jon,安德森,经理,“90,000,00”,03182006
页脚,3
Map文件:
这是修改后的
pattern-mapping.xml
文件。请注意,使用<group>
元素(myGroup)将所有内容封装到一个组中,这将强制BeanReader
一次性读取所有内容。我还将Header
和Footer
记录的maxOccurs
更改为1。另外,添加了collection="list" attribute to the
emp`记录使用提供的测试用例和修改后的Map文件,我们得到以下结果(由我重新格式化):
希望这个能帮上忙
gudnpqoy2#
从BeanIO 2.1.0开始,您可以通过如下配置流以JSON格式编写输出