I need to serialize some objects to a JSON and send to a WebService. How can I do it using the org.json library? Or I'll have to use another one? Here is the class I need to serialize:
public class PontosUsuario { public int idUsuario; public String nomeUsuario; public String CPF; public String email; public String sigla; public String senha; public String instituicao; public ArrayList<Ponto> listaDePontos; public PontosUsuario() { //criando a lista listaDePontos = new ArrayList<Ponto>(); } }
I only put the variables and the constructor of the class but it also have the getters and setters. So if anyone can help please
Use toJSON() Method to make class JSON serializable So we don't need to write custom JSONEncoder. This new toJSON() serializer method will return the JSON representation of the Object. i.e., It will convert custom Python Object to JSON string.
Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
Easy way to do it without annotations is to use Gson library
Simple as that:
Gson gson = new Gson(); String json = gson.toJson(listaDePontos);
One can use the Jackson library as well.
Add Maven Dependency:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </dependency>
Simply do this:
ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString( serializableObject );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With