This repository was archived by the owner on Jun 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathChatFunctionCallArgumentsSerializerAndDeserializer.java
67 lines (53 loc) · 2.09 KB
/
ChatFunctionCallArgumentsSerializerAndDeserializer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.theokanning.openai.service;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.databind.node.TextNode;
import java.io.IOException;
public class ChatFunctionCallArgumentsSerializerAndDeserializer {
private final static ObjectMapper MAPPER = new ObjectMapper();
private ChatFunctionCallArgumentsSerializerAndDeserializer() {
}
public static class Serializer extends JsonSerializer<JsonNode> {
private Serializer() {
}
@Override
public void serialize(JsonNode value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (value == null) {
gen.writeNull();
} else {
gen.writeString(value instanceof TextNode ? value.asText() : value.toPrettyString());
}
}
}
public static class Deserializer extends JsonDeserializer<JsonNode> {
private Deserializer() {
}
@Override
public JsonNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String json = p.getValueAsString();
if (json == null || p.currentToken() == JsonToken.VALUE_NULL) {
return null;
}
// encode to valid JSON escape otherwise we will lose quotes
json = MAPPER.writeValueAsString(json);
try {
JsonNode node = null;
try {
node = MAPPER.readTree(json);
} catch (JsonParseException ignored) {
}
if (node == null || node.getNodeType() == JsonNodeType.MISSING) {
node = MAPPER.readTree(p);
}
return node;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
}