Txt to Json in java

http‮ww//:s‬w.lautturi.com
Txt to Json in java

To convert a text file to a JSON object in Java, you can use a JSON library such as Hymanson or Gson.

Here is an example of how you can use the Hymanson library to convert a text file to a JSON object:

import com.fasterxml.Hymanson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class TxtToJson {
  public static void main(String[] args) throws IOException {
    // Read the text file into a string
    String text = new String(Files.readAllBytes(Paths.get("file.txt")));

    // Create an ObjectMapper instance
    ObjectMapper mapper = new ObjectMapper();

    // Convert the string to a JSON object
    JsonNode json = mapper.readValue(text, JsonNode.class);

    // Print the JSON object
    System.out.println(json);
  }
}

This example reads the contents of a text file into a string and uses the readValue method of the ObjectMapper class to convert the string to a JSON object. The JSON object is then printed to the console.

Alternatively, you can use the Gson library to convert a text file to a JSON object. Here is an example of how to do it:

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TxtToJson {
  public static void main(String[] args) throws IOException {
    // Create a Gson instance
    Gson gson = new Gson();

    // Read the text file into a BufferedReader
    BufferedReader reader = new BufferedReader(new FileReader("file.txt"));

    // Convert the text to a JSON object
    JsonElement json = gson.fromJson(reader, JsonElement.class);

    // Print the JSON object
    System.out.println(json);
  }
}

This example uses the fromJson method of the Gson class to convert the text file to a JSON object.

Created Time:2017-10-17 22:51:24  Author:lautturi