将JSON对象转换为JSON数组

时间:2012-07-23 03:13:21

标签: json web-services rest jsonp arrays

我遇到了问题。我的应用程序不会从我的Web服务加载资源,因为它的格式已经更改。

在我的Web服务返回这样的JSON数组之前:

[{"productid":2,"sku":"SKU-2","productname":"SMART NEW","productdesc":"description","category":"default category","price":2000.1,"picture":"http://10.23.20.50:8080/msos-ws/images/products/smart.gif","remarks":"remarks"}]

现在它返回一个JSON对象我想:

{"product":[{"category":"default category","picture":"http://localhost:8080/msos-ws/images/products/smart.gif","price":"480.0","productdesc":"Dragon Flash Disk (Special)","productid":"7","productname":"Kingston 8GB","remarks":"remarks","sku":"SKU-7"}]}

这是我在后端的代码:

@GET
@Override
@Produces("application/json")
public List<Product> findAll() {
        return prodManager.getProducts();
}

我正在返回一个List,所以它应该在数组中,对吗?

1 个答案:

答案 0 :(得分:0)

你得到的是一个键/值对,其中键是

product

和1元素数组是

[{"category":"default category","picture":"http://localhost:8080/msos-ws/images/products/smart.gif","price":"480.0","productdesc":"Dragon Flash Disk (Special)","productid":"7","productname":"Kingston 8GB","remarks":"remarks","sku":"SKU-7"}]

参考www.json.org/javadoc/org/json/JSONObject.html,看看以下方法:

public java.lang.Object get(java.lang.String key)

public JSONObject put(java.lang.String key,
                  java.util.Collection value)

现在,修改您的应用以加载资源应该很简单:)