简体   繁体   中英

Converting flatfile to JSON in Java

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM