Convert object to JSON in Android

169,842

Solution 1

Most people are using gson : check this

Gson gson = new Gson();
String json = gson.toJson(myObj);

Solution 2

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 "";
    }

}

Solution 3

Might be better choice:

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

Solution 4

download the library Gradle:

implementation 'com.google.code.gson:gson:2.9.0'

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);

Solution 5

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);
Share:
169,842

Related videos on Youtube

Thizzer
Author by

Thizzer

Software developer at heart. Interested in all things Tech.

Updated on April 03, 2022

Comments

  • Thizzer
    Thizzer about 2 years

    Is there a simple method to convert any object to JSON in Android?

  • Klaus Groenbaek
    Klaus Groenbaek over 7 years
    You don't need to add MappingJackson2HttpMessageConverter to RestTemplate, if the Jackson Jar is in the classpath it is added automatically.
  • Neria Nachum
    Neria Nachum over 7 years
    Why is this a better choice?
  • Thizzer
    Thizzer over 7 years
    Wanting to be able to convert an object to a JSON string does not necessarily mean you want the object's string representation to always be JSON.
  • Hesam
    Hesam over 7 years
    @NeriaNachum, The thing was in my mind when I answered having a class with a lot of attributes. Overriding its toString() method creates many String objects when you print in default way - generated by Android Studio or IntelliJ Idea - however, this is one line of code and using power of GsonBuilder.
  • Hesam
    Hesam over 7 years
    @Thizzer, You are absolutely right. I was thinking it is good to be shared and seen by developers (those who aren't familiar with approach at least). Then they will use whenever they need.
  • adnaan.zohran
    adnaan.zohran over 7 years
    I too feel this as better choice as the conversion can be handled from the model itself, abstracting out the implementation.
  • M at
    M at over 6 years
    Why we have no embedded method for toJson? But we have for fromJson ?
  • Bhimbim
    Bhimbim over 6 years
    i prefer this way, each object has their own stringify method, thank you for the insight !.
  • Matthew Read
    Matthew Read about 6 years
    This is the opposite of what was asked.
  • gumuruh
    gumuruh almost 4 years
    try to use gson they have it.
  • Frank Gue
    Frank Gue over 2 years
    But it is very complicated if you want to offuscate your code