[英]Converting flatfile to JSON in Java
I need to convert a flat file to a JSON file in Java.我需要在 Java 中将平面文件转换为 JSON 文件。
My flat file looks like this:我的平面文件如下所示:
customerInfo.firstName=abc
customerInfo.lastName=aaa
customerInfo.nickNames.0.name=bbb
customerInfo.nickNames.0.meaning=ccc
Here is the piece of code I am using:这是我正在使用的一段代码:
JSONParser parser = new JSONParser();
Object obj = null;
try {
//obj = parser.parse(new FileReader("src/main/resources/flatfileex.txt"));
JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader(new FileInputStream("src/main/resources/flatfileex.txt")));;
String flattenedJson = JsonFlattener.flatten(jsonObject.toJSONString());
System.out.println(flattenedJson);
} catch (FileNotFoundException | IOException | ParseException e) {
e.printStackTrace();
}
I am using jsonflattener dependency for the above code:我对上述代码使用 jsonflattener 依赖项:
<dependency>
<groupId>com.github.wnameless</groupId>
<artifactId>json-flattener</artifactId>
<version>0.1.0</version>
</dependency>
Getting error while parsing the file Unexcexpected character [c] at position 0. How to resolve this?解析文件时出错,位置 0 处出现意外字符 [c]。如何解决?
Your input file looks like a Java properties file, so you could try this:你的输入文件看起来像一个 Java 属性文件,所以你可以试试这个:
Properties prop = new Properties();
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("content.txt")){
prop.load(inputStream);
String contentAsJson = new ObjectMapper().writeValueAsString(prop);
System.out.print(contentAsJson);
} catch (IOException exception) {
System.out.println("Something went wrong!");
}
If your file contains如果您的文件包含
customerInfo.firstName=abc
customerInfo.lastName=aaa
customerInfo.nickNames.0.name=bbb
customerInfo.nickNames.0.meaning=ccc
It will print它会打印
{"customerInfo.lastName":"aaa","customerInfo.firstName":"abc","customerInfo.nickNames.0.name":"bbb","customerInfo.nickNames.0.meaning":"ccc"}
I guess that from here you can use json-flattener
.我想从这里你可以使用json-flattener
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.