Reputation: 462
I need to convert a flat file to a JSON file in Java.
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:
<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?
Upvotes: 0
Views: 1471
Reputation: 41
Your input file looks like a Java properties file, so you could try this:
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
.
Upvotes: 2