How to serialize Object to JSON?
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
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 );
The quickest and easiest way I've found to Json-ify POJOs is to use the Gson library. This blog post gives a quick overview of using the library.
You make the http request
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
You read the Buffer
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();
Create a JSONObject and pass the result string to the constructor:
JSONObject json = new JSONObject(result);
Parse the json results to your desired variables:
String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");
Do not forget to import:
import org.json.JSONObject;
GSON is easy to use and has relatively small memory footprint. If you loke to have even smaller footprint, you can grab:
https://github.com/ko5tik/jsonserializer
Which is tiny wrapper around stripped down GSON libraries for just POJOs