[英]Converting flatfile to JSON in Java
我需要在 Java 中將平面文件轉換為 JSON 文件。
我的平面文件如下所示:
customerInfo.firstName=abc
customerInfo.lastName=aaa
customerInfo.nickNames.0.name=bbb
customerInfo.nickNames.0.meaning=ccc
這是我正在使用的一段代碼:
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();
}
我對上述代碼使用 jsonflattener 依賴項:
<dependency>
<groupId>com.github.wnameless</groupId>
<artifactId>json-flattener</artifactId>
<version>0.1.0</version>
</dependency>
解析文件時出錯,位置 0 處出現意外字符 [c]。如何解決?
你的輸入文件看起來像一個 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!");
}
如果您的文件包含
customerInfo.firstName=abc
customerInfo.lastName=aaa
customerInfo.nickNames.0.name=bbb
customerInfo.nickNames.0.meaning=ccc
它會打印
{"customerInfo.lastName":"aaa","customerInfo.firstName":"abc","customerInfo.nickNames.0.name":"bbb","customerInfo.nickNames.0.meaning":"ccc"}
我想從這里你可以使用json-flattener
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.