Convert object to JSON in Android

2019-01-08 08:44发布

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

6条回答
在下西门庆
2楼-- · 2019-01-08 09:15

Might be better choice:

@Override
public String toString() {
    return new GsonBuilder().create().toJson(this, Producto.class);
}
查看更多
【Aperson】
3楼-- · 2019-01-08 09:21

This how you can convert a JSON string to JSON Object natively without using any external libraries and get corresponding values for a key. Hopefully the below should work.

String JSONstring = "{/"key1/":/"I am Value for Key1/"}";

//Import these libraries
import org.json.JSONException;
import org.json.JSONObject;

//Code below
try
{
String myVariable = jsonObject.optString("key1", "Fallback Value if key1 is not present");
System.out.println("Testing: "+ myVariable);
}
catch (JSONException e) {e.printStackTrace();}
查看更多
神经病院院长
4楼-- · 2019-01-08 09:29
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 "";
    }

}
查看更多
手持菜刀,她持情操
5楼-- · 2019-01-08 09:36

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);
查看更多
仙女界的扛把子
6楼-- · 2019-01-08 09:36

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.

查看更多
放荡不羁爱自由
7楼-- · 2019-01-08 09:37

Most people are using gson: https://github.com/google/gson

Gson gson = new Gson();
String json = gson.toJson(myObj);
查看更多
登录 后发表回答