generate a json file with java

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:

  • search algorithm name
  • time in ns to run the algorithm
  • this time in ns become ms.

Is there any way to transform 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 .json file in javascript or vice versa and turn it into a table (I do not know how to interface in java, so I found it easier to do this (in generating the json file in a table in html)).

    
asked by anonymous 30.04.2015 / 00:59

3 answers

6

Yes, using the json-simple library, 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();
    }
     }
}

So 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 at json.org.

    
30.04.2015 / 04:17
2

There's a google library called GSON  very simple to use. Download it, put it in 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);
    
30.04.2015 / 06:04
1

You can use the Java EE 7 JsonObject :

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

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

String jsonString = json.toString();
    
23.01.2017 / 18:10