Convert object to JSON in Android Convert object to JSON in Android java java

Convert object to JSON in Android


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:

@Overridepublic String toString() {    return new GsonBuilder().create().toJson(this, Producto.class);}