168

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

Thizzer
  • 16,153
  • 28
  • 98
  • 139

8 Answers8

335

Most people are using gson : check this

Gson gson = new Gson();
String json = gson.toJson(myObj);
Akshay
  • 2,506
  • 4
  • 34
  • 55
James L
  • 16,456
  • 10
  • 53
  • 70
64
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 "";
    }

}
Lodder
  • 19,758
  • 10
  • 59
  • 100
ingyesid
  • 2,864
  • 2
  • 23
  • 21
14

Might be better choice:

@Override
public String toString() {
    return new GsonBuilder().create().toJson(this, Producto.class);
}
Hesam
  • 52,260
  • 74
  • 224
  • 365
  • Why is this a better choice? – Neria Nachum Oct 23 '16 at 07:25
  • 1
    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. – Thizzer Oct 23 '16 at 11:49
  • @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 Oct 24 '16 at 00:24
  • @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. – Hesam Oct 24 '16 at 00:27
  • I too feel this as better choice as the conversion can be handled from the model itself, abstracting out the implementation. – adnaan.zohran Nov 24 '16 at 13:33
12

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);
Fattie
  • 27,874
  • 70
  • 431
  • 719
4

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);
Saeed Zarinfam
  • 9,818
  • 7
  • 59
  • 72
  • You don't need to add MappingJackson2HttpMessageConverter to RestTemplate, if the Jackson Jar is in the classpath it is added automatically. – Klaus Groenbaek Oct 11 '16 at 14:14
3

The Kotlin way

val json = Gson().toJson(myObj)
Rahul Mishra
  • 1,122
  • 1
  • 10
  • 25
2

As of Android 3.0 (API Level 11) Android has a more recent and improved JSON Parser.

http://developer.android.com/reference/android/util/JsonReader.html

Reads a JSON (RFC 4627) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.

Mob
  • 10,958
  • 6
  • 41
  • 58
1

Anyway, you know this

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

You might have forget to add @Expose

enter image description here

madhu527
  • 4,644
  • 1
  • 28
  • 29