Skip to content

Commit

Permalink
improved jsonb jdbc support, for issue #2332
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Mar 18, 2024
1 parent 109d97b commit 8724cf5
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
10 changes: 10 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/util/JdbcSupport.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.alibaba.fastjson2.util;

import com.alibaba.fastjson2.JSONB;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
Expand Down Expand Up @@ -527,6 +528,15 @@ public Object readJSONBObject(JSONReader jsonReader, Type fieldType, Object fiel
return null;
}

byte type = jsonReader.getType();
if (type == JSONB.Constants.BC_LOCAL_DATETIME) {
LocalDateTime ldt = jsonReader.readLocalDateTime();
Instant instant = ldt.atZone(jsonReader.getContext().getZoneId()).toInstant();
return createTimestamp(
instant.toEpochMilli(),
instant.getNano());
}

return readObject(jsonReader, fieldType, fieldName, features);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.alibaba.fastjson2.issues_2300;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONB;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.junit.jupiter.api.Test;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class Issue2332 {
@Test
public void test() {
DemoEntity entity = new DemoEntity();
DemoEntity2 entity2 = new DemoEntity2();

entity2.setNow(LocalDateTime.now());
byte[] jsonString2 = JSONB.toBytes(entity2);
// 不会报错
DemoEntity2 demoEntity3 = JSONB.parseObject(jsonString2, DemoEntity2.class);
assertEquals(entity2.now, demoEntity3.now);

entity.setNow(Timestamp.valueOf(LocalDateTime.now()));
String jsonString3 = JSON.toJSONString(entity2);
// 不会报错
DemoEntity2 demoEntity2 = JSON.parseObject(jsonString3, DemoEntity2.class);
assertEquals(entity2.now.truncatedTo(ChronoUnit.SECONDS), demoEntity2.now);

byte[] jsonb = JSONB.toBytes(entity);
DemoEntity entity1 = JSONB.parseObject(jsonb, DemoEntity.class);
assertEquals(entity.now, entity1.now);
}

@Data
public static class DemoEntity {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Timestamp now;
}

@Data
public static class DemoEntity2 {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime now;
}
}

0 comments on commit 8724cf5

Please sign in to comment.