0

I'm doing a school project (create a bus network), and they ask me to put the data (number of the bus and so on) into a json file.

Do you guys have a simple example for me please ? I'm using eclipse, and I tried to use the org.json.simple.JSONObject; library but it does not work.

Cordially

Balaure
  • 117
  • 8
  • There are many libraries to convert a java object into Json. Probably the most widely used are Jackson and Gson. After you get a Json object then you can write it to a file. Please share the code you are trying so we can help you. – Ezequiel Jun 28 '19 at 10:51

4 Answers4

0

Jackson is the de-facto standard library for reading and writing JSON with Java. It can also be used to read/write XML, YAML and other formats.

There are many tutorials on the web on how to use Jackson, such as http://www.studytrails.com/java/json/jackson-create-json/

General usage:

  • Create/confiure a ObjectMapper
  • Create your data beans, and optionally annotate them with Jackson annotations to fine-tune the serialization
  • Serialize/deserialize your beans using the object mapper.

Sophisticated example which also shows how to serialize from/to other formats, and how to use custom serialization: https://github.com/pwalser75/json-xml-yaml-test

Peter Walser
  • 15,208
  • 4
  • 51
  • 78
0

You can have a look at Java – Write to File and How do I create a file and write to it in Java?

With a POJO:

public class Data {

    private final String name;
    private final String id;

    public Data(final String name, final String id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public String getId() {
        return id;
    }
}

And this code using Jackson and ObjectMapper:

ObjectMapper objectMapper = new ObjectMapper();
Data data = new Data("abc", "123");
String jsonData = objectMapper.writeValueAsString(data);
Path path = Paths.get("myFile");
Files.write(path, jsonData.getBytes(StandardCharsets.UTF_8));
Thibaud Ledent
  • 1,446
  • 1
  • 7
  • 6
  • Thanks. If my data is inside an ArrayList, how can I put all that inside this json file ? For example, I've inside an ArrayList all the bus stop, in another one the bus inside the network and so on. – Balaure Jun 28 '19 at 11:04
  • You can create an object with the two lists: "Data myData = new Data(list1, list2);" or use the lists directly: "System.out.println(objectMapper.writeValueAsString(myList);" – Thibaud Ledent Jun 28 '19 at 11:14
  • Which import I need to be able to use this code ? Since it does not propose me an import :/ – Balaure Jun 28 '19 at 11:35
  • `import com.fasterxml.jackson.databind.ObjectMapper;` which can be imported with the [jackson-databind Maven dependency](https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.9.9) – Thibaud Ledent Jun 28 '19 at 12:51
  • I'm not using maven, since the project is well advanced. it says when I put it "create class ObjectMapper in package com.faster...." :/ – Balaure Jun 28 '19 at 13:02
  • I finally success to have those import. But I can not find the one for Data, it says it does not exist.. – Balaure Jun 28 '19 at 15:34
  • You have to create the class `Data` defined above – Thibaud Ledent Jun 30 '19 at 16:41
0

If you refer to the example posted here you can see how to handle lists: How to construct JSON data in Java

You can also just put an ArrayList as value instead an array of Strings. Jackson will do the rest for you.

arnonuem
  • 1,317
  • 6
  • 19
  • I need to create 2 new class ? I first thought that I just need to put some lines into my files – Balaure Jun 28 '19 at 11:48
  • You dont need to create model classes if you use generic HashMaps which i already posted here: https://stackoverflow.com/questions/56805274/how-to-construct-json-data-in-java – arnonuem Jun 28 '19 at 11:52
  • well, it does not recognize "ObjectMapper", which import I need to use ? – Balaure Jun 28 '19 at 11:56
  • yes you have to download or import it. If you use maven you gould just put a ``` com.fasterxml.jackson.core jackson-databind 2.9.8 ``` Take care to take the latest dependency you can look it up at https://search.maven.org/ – arnonuem Jun 28 '19 at 12:03
  • I'm not using maven :/ – Balaure Jun 28 '19 at 12:04
  • than grap the binary from somewhere - you really should use maven nowadays. You need to find com.fasterxml.jackson.core module which contains databinding. – arnonuem Jun 28 '19 at 12:06
  • well thanks, I don't know how to do it then, i'll try to find something – Balaure Jun 28 '19 at 12:12
0

Here is a file1.txt content:

{
"Name": "crunchify.com",
"Author": "App Shah",
"Company List": [
    "Compnay: eBay",
    "Compnay: Paypal",
    "Compnay: Google"
]
}

Java Code:

    package com.crunchify.tutorials;

    import java.io.FileWriter;
    import java.io.IOException;

    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;



    public class CrunchifyJSONFileWrite {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws IOException {

        JSONObject obj = new JSONObject();
        obj.put("Name", "crunchify.com");
        obj.put("Author", "App Shah");

        JSONArray company = new JSONArray();
        company.add("Compnay: eBay");
        company.add("Compnay: Paypal");
        company.add("Compnay: Google");
        obj.put("Company List", company);

        // try-with-resources statement based on post comment below :)
        try (FileWriter file = new FileWriter("/Users/<username>/Documents/file1.txt")) {
            file.write(obj.toJSONString());
            System.out.println("Successfully Copied JSON Object to File...");
            System.out.println("\nJSON Object: " + obj);
        }
    }
}
Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39
khaled
  • 9
  • 1
  • 4