关于Java:在Android中将对象转换为JSON

 2021-04-26 

Convert object to JSON in Android

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


大多数人都在使用gson:检查此

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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"";
    }

}


可能是更好的选择:

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


下载库Gradle:

1
compile 'com.google.code.gson:gson:2.8.2'

在方法中使用库。

1
2
3
4
5
6
7
8
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);


Spring for Android使用RestTemplate轻松做到这一点:

1
2
3
4
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);


从Android 3.0(API级别11)开始,Android具有更新和改进的JSON解析器。

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.


您也可以使用Jackson库(将其导入到项目中),创建一个convert方法,该方法使用当前的对象类对其进行序列化或反序列化:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

private String convertObjectToJson(ObjectClass object) {
        ObjectMapper mapper = new ObjectMapper();
        //By default all fields without explicit view definition are included, disable this
        mapper.configure(JsonParser.Feature.IGNORE_UNDEFINED, false);

        String jsonString ="";

        try {
            jsonString = mapper.writerWithView(ObjectClass.class).writeValueAsString(object);
            System.out.println(jsonString);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return jsonString;
    }

这样,您可以使用多个视图在POST / PUT / PATCH操作中发送不同的JSON对象字符串。