Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize Object to JSON?

Tags:

java

json

android

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

like image 215
Tiago Geanezini Avatar asked May 17 '13 11:05

Tiago Geanezini


People also ask

How do you make an object JSON serializable?

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.

How do you serialize an object into JSON in Java?

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.

What is serialization to 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).


2 Answers

Easy way to do it without annotations is to use Gson library

Simple as that:

Gson gson = new Gson(); String json = gson.toJson(listaDePontos); 
like image 166
Bitman Avatar answered Oct 13 '22 13:10

Bitman


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 ); 
like image 31
techjourneyman Avatar answered Oct 13 '22 13:10

techjourneyman