我希望我的JSON看起来像这样:
{
"information": [{
"timestamp": "xxxx",
"feature": "xxxx",
"ean": 1234,
"data": "xxxx"
}, {
"timestamp": "yyy",
"feature": "yyy",
"ean": 12345,
"data": "yyy"
}]
}
到目前为止的代码:
import java.util.List;
public class ValueData {
private List information;
public ValueData(){
}
public List getInformation() {
return information;
}
public void setInformation(List information) {
this.information = information;
}
@Override
public String toString() {
return String.format("{information:%s}", information);
}
}
和
public class ValueItems {
private String timestamp;
private String feature;
private int ean;
private String data;
public ValueItems(){
}
public ValueItems(String timestamp, String feature, int ean, String data){
this.timestamp = timestamp;
this.feature = feature;
this.ean = ean;
this.data = data;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getFeature() {
return feature;
}
public void setFeature(String feature) {
this.feature = feature;
}
public int getEan() {
return ean;
}
public void setEan(int ean) {
this.ean = ean;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
@Override
public String toString() {
return String.format("{timestamp:%s,feature:%s,ean:%s,data:%s}", timestamp, feature, ean, data);
}
}
我只是错过了如何使用Jackson将Java对象转换为JSON的部分:
public static void main(String[] args) {
// CONVERT THE JAVA OBJECT TO JSON HERE
System.out.println(json);
}
我的问题是:我的类是正确的吗?我必须调用哪个实例,以及如何实现这个JSON输出?
发布于 2013-04-03 19:31:38
要将您的
在JSON中使用Jackson:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
发布于 2014-05-17 14:38:15
这可能很有用:
objectMapper.writeValue(new File("c:\\employee.json"), employee);
// display to console
Object json = objectMapper.readValue(
objectMapper.writeValueAsString(employee), Object.class);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(json));
发布于 2015-05-21 23:09:37
只需遵循以下任意一项:
对于
杰克逊
它应该可以工作:
json映射器= ObjectMapper ObjectMapper();返回mapper.writeValueAsString(object);//将在字符串中返回json
对于
gson
它应该可以工作:
Gson gson = new Gson();return Response.ok(gson.toJson(yourClass)).build();
https://stackoverflow.com/questions/15786129
复制相似问题