使用Jackson将Java对象转换为JSON

Jus*_*irl 148 java json object jackson

我希望我的JSON看起来像这样:

{
    "information": [{
        "timestamp": "xxxx",
        "feature": "xxxx",
        "ean": 1234,
        "data": "xxxx"
    }, {
        "timestamp": "yyy",
        "feature": "yyy",
        "ean": 12345,
        "data": "yyy"
    }]
}
Run Code Online (Sandbox Code Playgroud)

代码到目前为止:

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

}
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我只是错过了如何用Jackson将Java对象转换为JSON的部分:

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

我的问题是:我的课程是否正确?我必须调用哪个实例以及如何实现此JSON输出?

Jea*_*art 391

object要用杰克逊转换你的JSON:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
Run Code Online (Sandbox Code Playgroud)

  • 库顺便说一下:import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; (11认同)
  • 唯一的问题是String从ObjectWriter中逃脱出来.使用:new JSONObject(ow.writeValueAsString(msg))如果它是通过RESTful等Web服务发出的. (8认同)
  • 天哪,谢谢你.我整个上午都在寻找.writer().现在,如果我能找到它的文档页面,我将全部设置. (3认同)
  • 我正面临这个错误,如何用你的代码解决没有找到类com.liveprocessor.LPClient.LPTransaction的序列化器,并且没有发现创建BeanSerializer的属性(为了避免异常,禁用SerializationFeature.FAIL_ON_EMPTY_BEANS)) (3认同)

小智 22

我知道这是旧的(我是java的新手),但我遇到了同样的问题.答案对我来说并不像新手那么清楚...所以我想我会加入我学到的东西.

我使用了第三方库来帮助实现:org.codehaus.jackson 所有下载都可以在这里找到.

对于基本JSON功能,您需要将以下jar添加到项目的库中: jackson-mapper-asljackson-core-asl

选择项目所需的版本.(通常你可以使用最新的稳定版本).

将它们导入项目库后,将以下行添加import到代码中:

 import org.codehaus.jackson.JsonGenerationException;
 import org.codehaus.jackson.map.JsonMappingException;
 import org.codehaus.jackson.map.ObjectMapper;
Run Code Online (Sandbox Code Playgroud)

使用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();
}
Run Code Online (Sandbox Code Playgroud)

结果应如下所示: {"firstName":"Sample","lastName":"User","email":"sampleU@example.com"}


Vic*_*cky 17

这可能很有用:

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));
Run Code Online (Sandbox Code Playgroud)


Cla*_*sos 9

你可以这样做:

String json = new ObjectMapper().writeValueAsString(yourObjectHere);
Run Code Online (Sandbox Code Playgroud)


She*_*ott 8

就这样做

 for jackson it's
         ObjectMapper mapper = new ObjectMapper();  
         return mapper.writeValueAsString(object);
         //will return json in string


 for gson it's:
            Gson gson = new Gson();
            return Response.ok(gson.toJson(yourClass)).build();
Run Code Online (Sandbox Code Playgroud)

  • 问题是关于`杰克逊`,而不是'格森` (13认同)
  • 这是方法的名称 (3认同)
  • 什么是 Response.ok ? (2认同)
  • @Codeversed Response是Jersey库中的一个类.Response.ok将返回状态码为200的JSON响应. (2认同)

Ven*_*Ren 6

您可以像这样使用 Google Gson

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

Gson gson = new Gson();
String jsonStr = gson.toJson(user);
Run Code Online (Sandbox Code Playgroud)