我希望我的 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<ValueItems> information;
public ValueData(){
}
public List<ValueItems> getInformation() {
return information;
}
public void setInformation(List<ValueItems> 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 输出?
要使用 Jackson 将您的 object
转换为 JSON:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
我知道这是旧的(而且我是 java 新手),但我遇到了同样的问题。而且答案对我来说不像新手那么清楚......所以我想我会添加我学到的东西。
我使用了第三方库来帮助完成这项工作:org.codehaus.jackson
可以找到所有相关下载here。
对于基本 JSON 功能,您需要将以下 jar 添加到项目的库中:jackson-mapper-asl 和 jackson-core-asl
选择您的项目需要的版本。 (通常您可以使用最新的稳定版本)。
将它们导入您的项目库后,将以下 import
行添加到您的代码中:
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
使用您希望转换为 JSON 并作为 RESTful Web 服务的一部分返回的 java 对象定义和分配的值
User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "sampleU@example.com";
ObjectMapper mapper = new ObjectMapper();
try {
// convert user object to json string and return it
return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException e) {
// catch various errors
e.printStackTrace();
}
结果应如下所示:{"firstName":"Sample","lastName":"User","email":"sampleU@example.com"}
只需遵循以下任何一项:
对于杰克逊,它应该可以工作: ObjectMapper mapper = new ObjectMapper();返回 mapper.writeValueAsString(object); //将返回字符串中的json
对于 gson,它应该可以工作: Gson gson = new Gson();返回 Response.ok(gson.toJson(yourClass)).build();
jackson
,而不是 Gson
这可能有用:
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));
你可以这样做:
String json = new ObjectMapper().writeValueAsString(yourObjectHere);
您可以像这样使用 Google Gson
UserEntity user = new UserEntity();
user.setUserName("UserName");
user.setUserAge(18);
Gson gson = new Gson();
String jsonStr = gson.toJson(user);
好吧,即使是接受的答案也没有完全输出 op 要求的内容。它输出 JSON 字符串,但转义了 "
个字符。所以,虽然可能有点晚,但我正在回答,希望它会对人们有所帮助!这是我的做法:
StringWriter writer = new StringWriter();
JsonGenerator jgen = new JsonFactory().createGenerator(writer);
jgen.setCodec(new ObjectMapper());
jgen.writeObject(object);
jgen.close();
System.out.println(writer.toString());
注意:要使投票最多的解决方案发挥作用,POJO 中的属性必须是 public
或具有公共 getter
/setter
:
默认情况下,Jackson 2 仅适用于公共字段或具有公共 getter 方法的字段——序列化具有所有字段私有或包私有的实体将失败。
尚未测试,但我相信此规则也适用于其他 JSON 库,如 google Gson。
public class JSONConvector {
public static String toJSON(Object object) throws JSONException, IllegalAccessException {
String str = "";
Class c = object.getClass();
JSONObject jsonObject = new JSONObject();
for (Field field : c.getDeclaredFields()) {
field.setAccessible(true);
String name = field.getName();
String value = String.valueOf(field.get(object));
jsonObject.put(name, value);
}
System.out.println(jsonObject.toString());
return jsonObject.toString();
}
public static String toJSON(List list ) throws JSONException, IllegalAccessException {
JSONArray jsonArray = new JSONArray();
for (Object i : list) {
String jstr = toJSON(i);
JSONObject jsonObject = new JSONObject(jstr);
jsonArray.put(jsonArray);
}
return jsonArray.toString();
}
}
不定期副业成功案例分享
JSONObject
的完全合格包是什么?我无法在 jackson-databind 库中找到它。