Most people are using gson : check this
Gson gson = new Gson();
String json = gson.toJson(myObj);
public class Producto {
int idProducto;
String nombre;
Double precio;
public Producto(int idProducto, String nombre, Double precio) {
this.idProducto = idProducto;
this.nombre = nombre;
this.precio = precio;
}
public int getIdProducto() {
return idProducto;
}
public void setIdProducto(int idProducto) {
this.idProducto = idProducto;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public Double getPrecio() {
return precio;
}
public void setPrecio(Double precio) {
this.precio = precio;
}
public String toJSON(){
JSONObject jsonObject= new JSONObject();
try {
jsonObject.put("id", getIdProducto());
jsonObject.put("nombre", getNombre());
jsonObject.put("precio", getPrecio());
return jsonObject.toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
Might be better choice:
@Override
public String toString() {
return new GsonBuilder().create().toJson(this, Producto.class);
}
download the library Gradle:
compile 'com.google.code.gson:gson:2.8.2'
To use the library in a method.
Gson gson = new Gson();
//transform a java object to json
System.out.println("json =" + gson.toJson(Object.class).toString());
//Transform a json to java object
String json = string_json;
List<Object> lstObject = gson.fromJson(json_ string, Object.class);
Spring for Android do this using RestTemplate easily:
final String url = "http://192.168.1.50:9000/greeting";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Greeting greeting = restTemplate.getForObject(url, Greeting.class);
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