简体   繁体   English

使用 Jackson 将 Java 对象转换为 JSON

[英]Converting Java objects to JSON with Jackson

I want my JSON to look like this:我希望我的 JSON 看起来像这样:

{
    "information": [{
        "timestamp": "xxxx",
        "feature": "xxxx",
        "ean": 1234,
        "data": "xxxx"
    }, {
        "timestamp": "yyy",
        "feature": "yyy",
        "ean": 12345,
        "data": "yyy"
    }]
}

Code so far:到目前为止的代码:

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

}

and

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

I just missing the part how I can convert the Java object to JSON with Jackson:我只是错过了如何使用 Jackson 将 Java 对象转换为 JSON 的部分:

public static void main(String[] args) {
   // CONVERT THE JAVA OBJECT TO JSON HERE
    System.out.println(json);
}

My Question is: Are my classes correct?我的问题是:我的课程正确吗? Which instance do I have to call and how that I can achieve this JSON output?我必须调用哪个实例以及如何实现此 JSON 输出?

To convert your object in JSON with Jackson:要使用 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);

I know this is old (and I am new to java), but I ran into the same problem.我知道这很旧(而且我是 Java 新手),但我遇到了同样的问题。 And the answers were not as clear to me as a newbie... so I thought I would add what I learned.答案对我来说不像新手那么清楚......所以我想我会补充我学到的东西。

I used a third-party library to aid in the endeavor: org.codehaus.jackson All of the downloads for this can be found here .我使用了第三方库来帮助完成这项工作: org.codehaus.jackson可以在此处找到所有相关下载。

For base JSON functionality, you need to add the following jars to your project's libraries: jackson-mapper-asl and jackson-core-asl对于基本 JSON 功能,您需要将以下 jar 添加到您的项目库中: jackson-mapper-asljackson-core-asl

Choose the version your project needs.选择您的项目需要的版本。 (Typically you can go with the latest stable build). (通常您可以使用最新的稳定版本)。

Once they are imported in to your project's libraries, add the following import lines to your code:将它们导入到您的项目库后,将以下import行添加到您的代码中:

 import org.codehaus.jackson.JsonGenerationException;
 import org.codehaus.jackson.map.JsonMappingException;
 import com.fasterxml.jackson.databind.ObjectMapper;

With the java object defined and assigned values that you wish to convert to JSON and return as part of a RESTful web service使用 Java 对象定义并分配您希望转换为 JSON 并作为 RESTful Web 服务的一部分返回的值

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

The result should looks like this: {"firstName":"Sample","lastName":"User","email":"sampleU@example.com"}结果应如下所示: {"firstName":"Sample","lastName":"User","email":"sampleU@example.com"}

This might be useful:这可能有用:

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

Just follow any of these:只需遵循以下任何一项:

  • For jackson it should work:对于杰克逊它应该工作:

     ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(object); //will return json in string
  • For gson it should work:对于gson它应该工作:

     Gson gson = new Gson(); return Response.ok(gson.toJson(yourClass)).build();

你可以这样做:

String json = new ObjectMapper().writeValueAsString(yourObjectHere);

You can use Google Gson like this您可以像这样使用 Google Gson

UserEntity user = new UserEntity();
user.setUserName("UserName");
user.setUserAge(18);

Gson gson = new Gson();
String jsonStr = gson.toJson(user);

Well, even the accepted answer does not exactly output what op has asked for.好吧,即使是接受的答案也不能完全输出 op 要求的内容。 It outputs the JSON string but with " characters escaped. So, although might be a little late, I am answering hopeing it will help people! Here is how I do it:它输出 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());

Note: To make the most voted solution work, attributes in the POJO have to be public or have a public getter / setter :注意:要使投票最多的解决方案起作用,POJO 中的属性必须是public或具有公开的getter / setter

By default, Jackson 2 will only work with fields that are either public, or have a public getter method – serializing an entity that has all fields private or package private will fail.默认情况下,Jackson 2 仅适用于公共字段或具有公共 getter 方法的字段 - 序列化具有所有字段私有或包私有的实体将失败。

Not tested yet, but I believe that this rule also applies for other JSON libs like google Gson.尚未测试,但我相信此规则也适用于其他 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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM