我有一个arraylist,如:
List skus = new ArrayList();
,输出
[{value=4, sequence=1, availableinventory=50, defining=size, skuid=24846457, partnumber=602016000967318},
{value=6, sequence=2, availableinventory=50, defining=size, skuid=24846459, partnumber=602016000967319},
{value=8, sequence=3, availableinventory=50, defining=size, skuid=24846462, partnumber=602016000967320},
{value=10, sequence=4, availableinventory=50, defining=size, skuid=24846468, partnumber=602016000967321},
{value=12, sequence=5, availableinventory=50, defining=size, skuid=24846476, partnumber=602016000967322},
{value=14, sequence=6, availableinventory=50, defining=size, skuid=24846484, partnumber=602016000967323},
{value=16, sequence=7, availableinventory=50, defining=size, skuid=24846492, partnumber=602016000967324}]
但我想将上面的arraylist转换为JSON响应,这是一个字符串生成器,如下所示。
StringBuilder jsonUIRespesponse = new StringBuilder();
[{"skuid":"24845337","value":"16","partnumber":"602016000967240","availableinventory":"50","sequence":"7","defining":"size"},
{"skuid":"24845325","value":"6","partnumber":"602016000967235","availableinventory":"50","sequence":"2","defining":"size"},
{"skuid":"24845326","value":"8","partnumber":"602016000967236","availableinventory":"50","sequence":"3","defining":"size"},
{"skuid":"24845327","value":"10","partnumber":"602016000967237","availableinventory":"50","sequence":"4","defining":"size"},
{"skuid":"24845328","value":"12","partnumber":"602016000967238","availableinventory":"50","sequence":"5","defining":"size"},
{"skuid":"24845329","value":"14","partnumber":"602016000967239","availableinventory":"50","sequence":"6","defining":"size"},
{"skuid":"24845324","value":"4","partnumber":"602016000967234","availableinventory":"50","sequence":"1","defining":"size"}]
答案 0 :(得分:0)
使用从Java对象转换为JSON结构的映射器,您可以非常轻松地完成此操作。我使用杰克逊,但还有其他实现。
首先确保您的Java项目中有Jackson库。如果您正在使用Maven,则必须添加依赖项。需要说明的是,JDK中不存在AFAIK常见的Json序列化器/反序列化器,因此您必须在项目中添加库,即JSR 353的参考实现:JSON Processing的Java API
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.3.3</version>
</dependency>
然后,您可以使用ObjectMapper
实用程序类转换Json中的Java对象。
import com.fasterxml.jackson.databind.ObjectMapper;
...
ObjectMapper mapper = new ObjectMapper();
String jsonResponse = mapper.writeValueAsString(skus);
或附加到StringBuilder
StringBuilder sb = new StringBuilder();
sb.append(mapper.writeValueAsString(skus));
答案 1 :(得分:0)
您可以使用杰克逊图书馆。
ObjectMapper OBJECT_MAPPER = new ObjectMapper();
StringWriter stringWriter = new StringWriter();
OBJECT_MAPPER.writeValue(stringWriter, YOUR_LIST);
return stringWriter.toString();