generate a json file with java

Asked

Viewed 7,156 times

8

Iterative insertion: 7841910ns - 7ms

Iterative selection: 2677762ns - 2ms

Iterative merge: 708154ns - 0ms

This algorithm was made in Java, in the java console is printed several values, being:

  • name of the search algorithm
  • time in ns to run the algorithm
  • that time in ns transformed into ms.

Is there any way to turn this data into a json file (generate a file using java) for me to read using a javascript script? the idea was to open this file. json in javascript or vice versa and turns it into a table (I don’t know how to interface in java, so I found it easier to do this (in generating the json file in an html table)).

3 answers

8

Yes, using the library json-simple, for example:

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class JsonExample {
     public static void main(String[] args) {

    JSONObject obj = new JSONObject();

    for (Object algoritmo : algoritmos){
        JSONArray tempos = new JSONArray();
        tempos.add(algoritmo.tempo_ms);
        tempos.add(algoritmo.tempo_ns);

        obj.put(algoritmo.nome, tempos);
    }
    try {

        FileWriter file = new FileWriter("/caminho/do/arquivo");
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
     }
}

Thus the following JSON structure will be generated:

{
     "Insertion iterativo": ["7841910ns", "7ms"],
     "Selection iterativo": ["2677762ns", "2ms"],
     "Merge iterativo": ["708154ns", "0ms"]
}

There are many other libraries to work with JSON in Java, as can be seen in json.org.

2

There is a google library called GSON very simple to use. Download it, put it into your project and use the following code.

//Instancia objeto responsável por manipular JSON
Gson gson = new Gson();

//Transformar objeto em JSON
String json = gson.toJson(meuObjeto);

//Transformar JSON em Objeto
meuObjeto = gson.fromJson(json, MeuObjeto.class);

1

You can use the Jsonobject of Java EE 7:

String nome = "Joao";
Integer idade = 30;

JsonObject json = Json.createObjectBuilder()
                        .add("nome", nome)
                        .add("idade", idade)
                        .build();

String jsonString = json.toString();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.