ProtoBeanUtil.java
8.33 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package com.tianting.infoloop.utils;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.google.protobuf.Message;
import com.google.protobuf.MessageOrBuilder;
import com.google.protobuf.util.JsonFormat;
import lombok.SneakyThrows;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ProtoBeanUtil {
private static Gson gson = getGson();
/**
* protoBean -> string
*
* @param sourceMessage protoBean
* @return string
*/
public static String protoToJson(MessageOrBuilder sourceMessage) {
try {
return JsonFormat.printer().includingDefaultValueFields().print(sourceMessage);
} catch (Exception e) {
throw new IllegalArgumentException("ProtoBeanUtil->toJson->errorMessage:proto序列化string异常", e);
}
}
@SuppressWarnings("unchecked")
public static <T extends Message> T jsonToProto(String json, Class<T> protoBean) {
try {
Constructor<T> declaredConstructor = protoBean.getDeclaredConstructor((Class<?>[]) null);
declaredConstructor.setAccessible(Boolean.TRUE);
T instance = declaredConstructor.newInstance();
final var builder = instance.toBuilder();
if (json == null || json.isEmpty() || json.trim().equals("{}")) {
return (T) builder.build();
}
JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
return (T) builder.build();
} catch (Exception e) {
throw new IllegalArgumentException("json to proto error", e);
}
}
@SuppressWarnings("unchecked")
public static <T extends Message> List<T> jsonToProtoList(String jsonArray, Class<T> protoBean) {
try {
if (jsonArray == null || jsonArray.isEmpty() || jsonArray.trim().equals("[]")) {
return new ArrayList<>();
}
Constructor<T> declaredConstructor = protoBean.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
List<T> protoList = new ArrayList<>();
JsonArray jsonElements = JsonParser.parseString(jsonArray).getAsJsonArray();
for (JsonElement jsonElement : jsonElements) {
T instance = declaredConstructor.newInstance();
Message.Builder builder = instance.toBuilder();
JsonFormat.parser().ignoringUnknownFields().merge(jsonElement.toString(), builder);
protoList.add((T) builder.build());
}
return protoList;
} catch (Exception e) {
throw new IllegalArgumentException("jsonArray to protoList error", e);
}
}
public static String protoListToJson(List<? extends Message> sourceList) {
try {
StringBuilder jsonArrayBuilder = new StringBuilder();
jsonArrayBuilder.append("[");
for (int i = 0; i < sourceList.size(); i++) {
String json = protoToJson(sourceList.get(i));
jsonArrayBuilder.append(json);
if (i < sourceList.size() - 1) {
jsonArrayBuilder.append(",");
}
}
jsonArrayBuilder.append("]");
return jsonArrayBuilder.toString();
} catch (Exception e) {
throw new IllegalArgumentException("ProtoList to jsonArray error", e);
}
}
/**
* @desc: String 转 Builder对象
*/
private static <M extends Message.Builder> void jsonToBuilder(M targetBuilder, String json) {
try {
JsonFormat.parser().ignoringUnknownFields().merge(JSONUtil.writeAsJson(json), targetBuilder);
} catch (Exception e) {
throw new IllegalArgumentException("ProtoBeanUtil->JsonToBuilder->errorMessage:json 转 Builder对象异常", e);
}
}
/**
* @desc: JavaBean 转 Builder对象
*/
private static <M extends Message.Builder, T> M beanToBuilder(T beanSource, Class<M> targetBuilderClass) {
try {
Constructor<M> declaredConstructor = targetBuilderClass.getDeclaredConstructor((Class<?>[]) null);
declaredConstructor.setAccessible(Boolean.TRUE);
M instance = declaredConstructor.newInstance();
Gson gson = getGson();
String json = gson.toJson(beanSource);
jsonToBuilder(instance, json);
return instance;
} catch (Exception e) {
throw new IllegalArgumentException("ProtoBeanUtil->beanToBuilder->errorMessage:JavaBean 转 Builder对象异常", e);
}
}
/**
* @desc: javaBean 转 Proto
*/
@SneakyThrows
@SuppressWarnings("unchecked")
public static <M extends Message, T> M beanToProto(T bean, Class<M> targetProtoClass) {
Constructor<M> declaredConstructor = targetProtoClass.getDeclaredConstructor((Class<?>[]) null);
declaredConstructor.setAccessible(Boolean.TRUE);
M instance = declaredConstructor.newInstance();
Gson gson = getGson();
String json = gson.toJson(bean);
Message.Builder builder = instance.toBuilder();
jsonToBuilder(builder, json);
return (M) builder.build();
}
/**
* @desc: javaBean 列表 转 ProtoBean 列表
*/
@SuppressWarnings("unchecked")
public static <M, T extends Message> List<T> beanListToProtoList(Collection<M> beanSourceList, Class<T> protoBean) {
try {
List<T> resultList = new ArrayList<>();
for (Object bean : beanSourceList) {
Constructor<T> declaredConstructor = protoBean.getDeclaredConstructor((Class<?>[]) null);
declaredConstructor.setAccessible(Boolean.TRUE);
T instance = declaredConstructor.newInstance();
Class<? extends Message.Builder> aClass = instance.toBuilder().getClass();
Message.Builder builder = beanToBuilder(bean, aClass);
resultList.add((T) builder.build());
}
return resultList;
} catch (Exception e) {
throw new IllegalArgumentException("ProtoBeanUtil->beanListToProtoList->errorMessage:javaBean 列表 转 ProtoBean 列表异常", e);
}
}
private static Gson getGson() {
if (gson != null) {
return gson;
}
gson = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, new TypeAdapter<LocalDateTime>() {
@Override
public void write(JsonWriter out, LocalDateTime value) throws IOException {
if (value != null) {
out.value(LocalDateTimeUtil.toEpochMilli(value));
} else {
out.nullValue();
}
}
@Override
public LocalDateTime read(JsonReader in) throws IOException {
return LocalDateTimeUtil.of(Long.parseLong(in.nextString()));
}
})
.registerTypeAdapter(LocalDate.class, new TypeAdapter<LocalDate>() {
@Override
public void write(JsonWriter out, LocalDate value) throws IOException {
if (value != null) {
out.value(LocalDateTimeUtil.toEpochMilli(value));
} else {
out.nullValue();
}
}
@Override
public LocalDate read(JsonReader in) throws IOException {
return LocalDate.ofInstant(Instant.ofEpochMilli(Long.parseLong(in.nextString())), ZoneId.of("Asia/Shanghai"));
}
}
).create();
return gson;
}
}