在Android中将对象转换为JSON

Thy*_*hys 115 java rest android json

有没有一种简单的方法可以将任何对象转换为Android中的JSON?

Jam*_*s L 244

大多数人都在使用gson:https://github.com/google/gson

Gson gson = new Gson();
String json = gson.toJson(myObj);
Run Code Online (Sandbox Code Playgroud)

  • 还有杰克逊. (14认同)
  • 为什么我们没有toJson的嵌入方法?但我们有来自fromJson? (4认同)

ing*_*sid 56

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

}
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这种方式,每个对象都有自己的字符串化方法,谢谢你的洞察力! (2认同)

Hes*_*sam 9

可能是更好的选择:

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


小智 7

下载库 Gradle:

compile 'com.google.code.gson:gson:2.8.2'
Run Code Online (Sandbox Code Playgroud)

在方法中使用库。

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);
Run Code Online (Sandbox Code Playgroud)