标签: jackson2

Jackson - 使用自定义 PrettyPrinter 和自定义 JsonSerializer

我正在使用 Jackson v2.8.2 将 JSON 序列化到文件中。

我创建了一个自定义序列化器并实现了serialize根据需要自定义 JSON 输出的方法。

我按如下方式调用序列化器:

// myClass is the object I want to serialize

SimpleModule module = new SimpleModule();
module.addSerializer(MyClass.class, new MySerializer());

ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
mapper.registerModule(module);

try 
{
    mapper.writeValue(new File("json.txt"), myClass);
}

catch (JsonProcessingException e) 
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

JSON 文件已创建,内容看起来不错。

该文件的格式根据DefaultPrettyPrinter但我想使用我自己的自定义PrettyPrinter,我已经实现了。

我怎么做?

我尝试过以下方法:

MyPrettyPrinter myPrettyPrinter = new MyPrettyPrinter();
mapper.writer(myPrettyPrinter);
mapper.writeValue(new File("json.txt"), myClass);
Run Code Online (Sandbox Code Playgroud)

但这并没有调用我的自定义打印机。

java json jackson jackson2

3
推荐指数
1
解决办法
3568
查看次数

阻止杰克逊将数字读取为字符串

Jackson 将输入数字读取为字符串。作为下面的示例,Student 类将名称 4567 读取为字符串。

例如:输入

{
name: 4567
...
}
Run Code Online (Sandbox Code Playgroud)

Java类

Class Student {

String name;
...
}
Run Code Online (Sandbox Code Playgroud)

Jackson 正在解析 JSON 文本并将数字值映射到字符串字段,我不需要类型转换,即将数字转换为字符串。在这种情况下,Jackson 将值从 int (4567) 转换为 String("4567")。如果提供的其他类型失败,此行为如何更改以引发异常?

java jackson jackson2

3
推荐指数
1
解决办法
2867
查看次数

jackson禁用@JsonFormat注释

我正在使用 jackson 库,并且遇到了一种情况,我想在序列化/反序列化时使用 objectmapper 禁用 @JsonFormat 注释。

我的 Api 代码位于第 3 方库中,因此我无法删除/添加任何注释,因此 objectMapper 是唯一的选择。

API类:

public class ApiClass {

  @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
  private DateTime time;

}
Run Code Online (Sandbox Code Playgroud)

我的代码:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.configure(Feature.ALLOW_COMMENTS, true);
objectMapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.setSerializationInclusion(Include.NON_ABSENT);
objectMapper.registerModule(new JodaModule());
objectMapper.registerModule(new JavaTimeModule());

String str = " {\"time\": \"2012-05-01\"}";

ApiClass msg = objectMapper.readValue(str, ApiClass.class);
Run Code Online (Sandbox Code Playgroud)

我希望这次转换能够成功进行。

目前我得到: com.fasterxml.jackson.databind.JsonMappingException:格式无效:“2012-05-01”太短

请在这里帮助我。

提前致谢

java jackson jackson-dataformat-xml jackson2 jackson-databind

3
推荐指数
1
解决办法
3179
查看次数

java.lang.NoSuchMethodError使用Jackson Core Streaming API

我正在使用Jackson Core版本2.8.3,但为什么我一直在使用java.lang.NoSuchMethodError?我没有使用任何其他Jackson的模块,只使用核心(流媒体)API

Object[] result = imageGenerator.generate(lowerBound, upperBound, fileNames);
MWNumericArray array = (MWNumericArray)result[0];
try (Writer writer = response.getWriter();
     JsonGenerator generator = res.getJsonFactory().createGenerator(writer)) {

     generator.writeStartObject();
         generator.writeFieldName("dimension");
         generator.writeArray(array.getDimensions(), 0, 2); // java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonGenerator.writeArray([III)V

         int[] pixels = array.getIntData();
         generator.writeFieldName("pixels");
         generator.writeArray(pixels, 0, pixels.length);
     generator.writeEndObject();
}
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪

at servlet.IonImageGeneratorServlet.processRequest(IonImageGeneratorServlet.java:48)
at servlet.IonImageGeneratorServlet.doGet(IonImageGeneratorServlet.java:80)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:305)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at …
Run Code Online (Sandbox Code Playgroud)

java json jackson jackson2

2
推荐指数
1
解决办法
1万
查看次数

Jackson,将纯 JSON 数组反序列化为单个 Java 对象

外部服务提供带有普通/原始元素的 JSON 数组(因此没有字段名称,并且没有嵌套的 JSON 对象)。例如:

["Foo", "Bar", 30]
Run Code Online (Sandbox Code Playgroud)

我想使用 Jackson 将其转换为以下 Java 类的实例:

["Foo", "Bar", 30]
Run Code Online (Sandbox Code Playgroud)

(如果需要,可以对此类进行调整。)

问题:是否可以使用类似的方法将此 JSON 反序列化为 Java?

Person p = new ObjectMapper().readValue(json, Person.class);
Run Code Online (Sandbox Code Playgroud)

或者这只能通过为此 Person 类编写自定义 Jackson 反序列化器来实现?

我确实尝试了以下方法,但没有成功:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class Person {
    private String firstName;
    private String lastName;
    private int age;

    @JsonCreator
    public Person(
            @JsonProperty(index = 0) String firstName, 
            @JsonProperty(index = 1) String lastName, 
            @JsonProperty(index = 2) int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age …
Run Code Online (Sandbox Code Playgroud)

java json jackson jackson2 jackson-databind

2
推荐指数
1
解决办法
2883
查看次数

Spring Rest 模板中的哑剧类型无效?

我只是想发出一个简单的 REST 请求,如下所示

\n\n
String url = "some url";\nMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();\nheaders.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);\nheaders.add(HttpHeaders.AUTHORIZATION, "some authorization");\nRestTemplate restTemplate = new RestTemplate();\nrestTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());\nBody body = new Body();\nbody.setRemarks("test");\norg.springframework.http.HttpEntity request = new org.springframework.http.HttpEntity(body, headers);\ntry {\n    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, request, String.class);\n    System.out.println("Status Response: "+ response.getStatusCode() +". Body: "+ response.getBody());\n} catch (HttpClientErrorException | HttpServerErrorException e) {\n    e.printStackTrace();\n} catch (Exception e) {\n    e.printStackTrace();\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

问题是每次我在 Java 中执行此操作时,结果都是不可预测的,我通常会一直收到此错误。

\n\n
org.springframework.http.InvalidMediaTypeException: Invalid mime type "text/plain, application/json, application/json, application/*+json, application/*+json, */*; charset=UTF-8": Invalid token character \',\' in …
Run Code Online (Sandbox Code Playgroud)

java spring resttemplate spring-rest jackson2

2
推荐指数
1
解决办法
3万
查看次数

jackson kotlin - 无法从 START_OBJECT 令牌反序列化 `java.util.ArrayList` 的实例

我从 Fitbit API 得到一个 json 字符串。我想在 List 对象中保存日期时间和值字段。我正在使用 jackson 模块 kotlin。我为此创建了 ActivitiesSteps 数据类。

我不知道如何避免“活动步骤”字段,我被卡住了。

这是 JSON 正文(在我下面的代码中的 readValue 方法的变量“jsonSteps”中提供):

  {  
   "activities-steps":[  
      {  
         "dateTime":"2018-04-17",
         "value":"11045"
      },
      {  
         "dateTime":"2018-04-18",
         "value":"14324"
      },
      {  
         "dateTime":"2018-05-16",
         "value":"11596"
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

这是我用来保存数据的类:

data class ActivitiesSteps(var dateTime: String, var value: String)
Run Code Online (Sandbox Code Playgroud)

这是我使用杰克逊的代码:

val mapper = jacksonObjectMapper()
val stepsList = mapper.readValue<List<ActivitiesSteps>>(jsonSteps)
Run Code Online (Sandbox Code Playgroud)

并抛出以下异常:

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: 
Cannot deserialize instance of `java.util.ArrayList` out of 
START_OBJECT token at 

[Source: (String)"{"activities-steps":[
{"dateTime":"2018-04-17","value":"11045"},
{"dateTime":"2018-04-25","value":"8585"},
{"dateTime":"2018-04-26","value":"11218"},
{"dateTime":"2018-04-27","value":"10462"},
{"dateTime":"2018-04"[truncated 762 chars]; line: 1, …
Run Code Online (Sandbox Code Playgroud)

java json kotlin jackson2

2
推荐指数
1
解决办法
1927
查看次数

JacksonFactory的gradle依赖是什么?

我的程序需要使用 JacksonFactory,但依赖项不起作用,我发现implementation group: 'com.google.api-client', name: 'google-api-client-jackson2', version: '1.31.3'它只能在版本 1.20.0中工作,但是当我使用此版本时 Android Studio 要求我更新版本并返回错误。

我的代码是private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

请帮帮我!

jackson2

2
推荐指数
1
解决办法
1637
查看次数

Spring MVC:使用 Jackson objectMapper 将查询参数反序列化为 POJO

Spring Web应用程序配置包含ObjectMapper像这样配置的Jackson

  objectMapper.disable(ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
  objectMapper.registerModule(new JavaTimeModule())
Run Code Online (Sandbox Code Playgroud)

JavaTimeModule添加来处理 的反序列化ZonedDateTime。有两个端点处理包含ZonedDateTime. POJO是这样的:

class MyRequest {
  ZonedDateTime from
  ZonedDateTime to
}
Run Code Online (Sandbox Code Playgroud)

具有端点的控制器是:

@Slf4j
@RestController
class MyController {

  @GetMapping('/pojo')
  void getPojo(MyRequest myRequest) {
    log.debug("Request received: $myRequest")
  }

  @PostMapping('/pojo')
  void postPojo(@RequestBody MyRequest myRequest) {
    log.debug("Request received: $myRequest")
  }
}
Run Code Online (Sandbox Code Playgroud)

当我发送带有正文的 POST /pojo 时

{"from": "2017-03-15T00:00:00Z", "to": "2017-03-16T00:00:00Z"}
Run Code Online (Sandbox Code Playgroud)

响应为200,反序列化成功。

相反,当我发送

GET /pojo?from=2017-03-15T00:00:00Z&to=2017-03-15T00:00:00Z
Run Code Online (Sandbox Code Playgroud)

收到 400 Bad Request 错误

Failed to convert from type [java.lang.String] to type [java.time.ZonedDateTime] for value '2017-03-15T00:00:00Z'
Run Code Online (Sandbox Code Playgroud)

这是有道理的,因为在 GET …

spring-mvc deserialization spring-boot jackson2

1
推荐指数
1
解决办法
2971
查看次数

JsonMappingException:没有单字符串构造函数/工厂方法

[这不是“ 无法从JSON字符串实例化类型的值的重复项没有单字符串构造函数/工厂方法:这是简单得多的POJO和JSON。就我而言,解决方案也有所不同。]

我要解析的JSON并通过以下方式创建POJO:

{
    "test_mode": true,
    "balance": 1005,
    "batch_id": 99,
    "cost": 1,
    "num_messages": 1,
    "message": {
        "num_parts": 1,
        "sender": "EXAMPL",
        "content": "Some text"
    },
    "receipt_url": "",
    "custom": "",
    "messages": [{
        "id": 1,
        "recipient": 911234567890
    }],
    "status": "success"
}
Run Code Online (Sandbox Code Playgroud)

如果响应恰好是错误,则看起来像:

{
    "errors": [{
        "code": 80,
        "message": "Invalid template"
    }],
    "status": "failure"
}
Run Code Online (Sandbox Code Playgroud)

这是我定义的POJO:

@Data
@Accessors(chain = true)
public class SmsResponse {

    @JsonProperty(value = "test_mode")
    private boolean testMode;

    private int balance;

    @JsonProperty(value = "batch_id")
    private int batchId;

    private …
Run Code Online (Sandbox Code Playgroud)

java json jackson2

1
推荐指数
1
解决办法
3127
查看次数

jackson @JsonGetter 和 @JsonSetter 如何工作

我正在使用 jackson 2.10.0 ( https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core/2.10.0 ),以下是一个简单的测试用例

Person类定义如下,对于setter,我使用了@JsonSetter注解,而没有使用@JsonGetter作为getter,

import com.fasterxml.jackson.annotation.JsonProperty;

public class Person {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    @JsonSetter("first_name")
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @JsonSetter("last_name")
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后,我创建一个 Person 对象,并将其序列化为字符串,

import com.fasterxml.jackson.databind.ObjectMapper;


public class Person3Test2 {
    public static void main(String[] args) throws Exception {
        Person p = new Person();
        p.setFirstName("abc");
        p.setLastName("def");
        String str …
Run Code Online (Sandbox Code Playgroud)

java jackson jackson2 jackson-databind

1
推荐指数
1
解决办法
7847
查看次数