【问题标题】:Convert object to JSON in Android在 Android 中将对象转换为 JSON
【发布时间】:2011-07-31 01:49:37
【问题描述】:

有没有简单的方法在Android中将任何对象转换为JSON?

【问题讨论】:

    标签: java android json rest


    【解决方案1】:

    大多数人都在使用 gson:check this

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

    【讨论】:

    • 为什么我们没有嵌入toJson的方法?但是我们有 fromJson 吗?
    • 尝试使用他们有的gson。
    • 但是如果你想offuscate你的代码是非常复杂的
    【解决方案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 "";
        }
    
    }
    

    【讨论】:

    • 我更喜欢这种方式,每个对象都有自己的stringify方法,谢谢你的见解!。
    【解决方案3】:

    可能是更好的选择:

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

    【讨论】:

    • 为什么这是一个更好的选择?
    • 希望能够将对象转换为 JSON 字符串并不一定意味着您希望对象的字符串表示始终为 JSON。
    • @NeriaNachum,当我回答有一个具有很多属性的课程时,我的脑海中浮现出这件事。当您以默认方式打印时覆盖其toString() 方法会创建许多 String 对象 - 由 Android Studio 或 IntelliJ Idea 生成 - 但是,这是一行代码并使用 GsonBuilder 的强大功能。
    • @Thizzer,你是绝对正确的。我认为开发人员(至少不熟悉方法的人)分享和查看是件好事。然后他们会在需要时使用。
    • 我也觉得这是更好的选择,因为可以从模型本身处理转换,抽象出实现。
    【解决方案4】:

    下载 Gradle 库:

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

    在方法中使用库。

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

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

      • 您不需要将 MappingJackson2HttpMessageConverter 添加到 RestTemplate,如果 Jackson Jar 在类路径中,它会自动添加。
      【解决方案6】:

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

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

      将 JSON (RFC 4627) 编码值读取为令牌流。这 流包含两个文字值(字符串、数字、布尔值和 nulls) 以及对象和数组的开始和结束分隔符。 令牌以深度优先顺序遍历,与 它们出现在 JSON 文档中。在 JSON 对象中,名称/值 对由单个标记表示。

      【讨论】:

      • 这与所要求的相反。
      【解决方案7】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-16
        • 1970-01-01
        • 1970-01-01
        • 2014-10-24
        相关资源
        最近更新 更多