2011-04-06 226 views

回答

175

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

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

并且还杰克逊。 – Mob 2011-12-08 13:48:48

+1

为什么我们没有toJson的嵌入方法?但是我们从杰森来? – 2017-11-22 10:31:22

3

就Android 3.0(API等级11)的Android有一个较新的和改进的JSON解析器。

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

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

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

} 
+0

我更喜欢这种方式,每个对象都有自己的stringify方法,谢谢你的洞察! – Bhimbim 2017-12-18 04:33:59

2

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

您不需要将MappingJackson2HttpMessageConverter添加到RestTemplate,如果Jackson Jar在类路径中,它会自动添加。 – 2016-10-11 14:14:43

-1

这如何可以一个JSON字符串JSON对象转换本身,而无需使用任何外部库,并得到相应的值的关键。希望下面的工作。

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();} 
+2

这不是一个问题的答案。此外jsonObject在这里是未知的。 – CoolMind 2016-04-08 13:02:18

7

可能是更好的选择:

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

为什么这是一个更好的选择? – 2016-10-23 07:25:14

+0

希望能够将对象转换为JSON字符串并不一定意味着您希望对象的字符串表示始终为JSON。 – Thys 2016-10-23 11:49:08

+0

@NeriaNachum,当我回答有很多属性的课程时,我脑海中浮现出这样的东西。当以默认方式打印时,覆盖它的'toString()'方法会创建许多String对象 - 由Android Studio或IntelliJ Idea生成 - 但是,这是一行代码并使用GsonBuilder的强大功能。 – Hesam 2016-10-24 00:24:01