@UtilityClass
@Slf4j
public class GsonUtils {
private static final Gson GSON = new Gson();
public static String toJsonStr(Object object) {
return GSON.toJson(object);
}
public static String toJsonStr(Object obj, Type type) {
return GSON.toJson(obj, type);
}
public static <T> T fromJson(String json, Class<T> classOfT) {
return GSON.fromJson(json, classOfT);
}
public static <T> T fromJson(String json, Type typeOfT) {
return GSON.fromJson(json, typeOfT);
}
public static String toJson(Object object) {
try {
return GSON.toJson(object);
} catch (Exception e) {
log.error("序列化失败", e);
}
return StringUtils.EMPTY;
}
}
String str = "{\"status\":{\"code\":0,\"__isset_bit_vector\":[1]},\"poiId\":1}";
TResponse tResponseA = GsonUtils.fromJson(str, TResponse.class);
String.format("Duplicate asyncCreateTask request with requestId=%s, billNo=%s, finish it fast.", request.getRequestId(), request.getNo());
map.put("0915", "1");
map.put("0916", "2");
String jsonStr = GsonUtils.toJsonStr(map);
Map json2Map = GsonUtils.fromJson(jsonStr,new TypeToken>(){}.getType());
如果类中有Date类型的属性字段,则需要在创建gson的时候设置一下日期格式
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd")
.create();
System.out.println(gson.toJson(new Date()));
List<SkuDTO> list = GsonUtils.fromJson(jsonStr,new TypeToken<List<SkuDTO>>(){}.getType());
List<Long> list2 = GsonUtils.fromJson(Lists.newArrayList(1L,2L), new TypeToken<List<Long>>() {}.getType());
public void t() throws JSONException {
String s1 = "{\"skuId\":1,\"skuName\":\"test\",\"temp\":2,\"address\":\"bj\"}";
String s2 = "{\"skuId\":1,\"skuName\":\"test\",\"temp\":3,\"author\":\"mjp\"}";
// 方式一:
JSONCompareResult result = JSONCompare.compareJSON(s1, s2, JSONCompareMode.STRICT);
<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
// 1中有2中没有
System.out.println(result.isMissingOnField());
List<FieldComparisonFailure> fieldMissing = result.getFieldMissing();
for (FieldComparisonFailure fieldComparisonFailure : fieldMissing) {
System.out.println(fieldComparisonFailure.getExpected());//address
}
// 2中有1中没有
System.out.println(result.isUnexpectedOnField());
List<FieldComparisonFailure> fieldUnexpected = result.getFieldUnexpected();
for (FieldComparisonFailure fieldComparisonFailure : fieldUnexpected) {
System.out.println(fieldComparisonFailure.getActual());//author
}
// 1中2中都有,但是val值不一样
System.out.println(result.isFailureOnField());
List<FieldComparisonFailure> list = result.getFieldFailures();
for (FieldComparisonFailure fieldComparisonFailure : list) {
System.out.println(fieldComparisonFailure.getField());//temp
System.out.println(fieldComparisonFailure.getActual());//3
System.out.println(fieldComparisonFailure.getExpected());//2
}
// 方式二:
HashMap<String, Object> diffMap = Maps.newHashMap();
Gson gson = new Gson();
Map<String,Object> json1Map = gson.fromJson(s1,new TypeToken<HashMap<String,Object>>(){}.getType());
Map<String,Object> json2Map = gson.fromJson(s2,new TypeToken<HashMap<String,Object>>(){}.getType());
for (Map.Entry<String, Object> entry : json1Map.entrySet()) {
String k1 = entry.getKey();
Object v1 = entry.getValue();
Object v2 = json2Map.get(k1);
// 1中有2中没有
if (v2 == null) {
diffMap.put(k1, v1);
continue;
}
// 1中2中都有,但是不一样
if (!Objects.equals(v1, v2)){
diffMap.put(k1, "expect:" + v1 + ", actual:" + v2);
}
}
json2Map.forEach((k2, v2) -> {
Object v1 = json1Map.get(k2);
// 2中有1中没有
if (v1 == null) {
diffMap.put(k2, v2);
}
});
System.out.println(diffMap);//{temp=expect:2.0, actual:3.0, address=bj, author=mjp}
}
Long billType = 1L;
System.out.println("a" + StringUtils.leftPad(billType + "", 5, "0"));// a00001
即在billType的左侧补0,直到00001形成5位为止
右侧填充和两侧填充api如下:
public static String leftPad(final String str, final int size, String padStr)
public static String center(String str, final int size, String padStr)
参考:https://blog.csdn.net/lonely_fireworks/article/details/7962171
int time = 3;
String nameParis = String.format("达到了最大次数%s次", time);
String contentFormat = "您今天售卖的【%s】支商品有较高可能发生售罄,预估销售损失pcs【%s】件,预估销售损失额【%s" +"】元,需联系补货,请点击“[及时处理|%s]”查看详情。";
String url = "sell.out.warning.link:https://xxx.xxx.xxx" + ".com?warnType=%s&categoryId=%s"
String result = String.format(contentFormat, skuCount, salePcs.stripTrailingZeros().toPlainString(),
saleGmv.stripTrailingZeros().toPlainString(),
String.format(url, warnType, categoryId));
1、将warnTpe和categoryId,填充到url中,成为一个完整的连接url
2、sku数,pcs,GMV,及时处理链接url 四个字端值,填充到contentFormat的%s中
String s = "大家好才是真的好";
String truncate = StringUtils.truncate(s, 2, 4);
System.out.println(truncate);//好才是真
https://www.runoob.com/java/java-string-split.html
public static boolean isNotEmpty(String str):判断某字符串是否非空,这里不能排除空格字符,即StringUtils.isNotEmpty(" ") = true
下面是示例:
StringUtils.isNotEmpty(null) = false
StringUtils.isNotEmpty("") = false
StringUtils.isNotEmpty(" ") = true
public static boolean isNotBlank(String str)
判断某字符串是否不为空且长度不为0且不由空白符(whitespace)构成,即StringUtils.isNotBlank(" ") = false
下面是示例:
StringUtils.isNotBlank(null) = false
StringUtils.isNotBlank("") = false
StringUtils.isNotBlank(" ") = false
所以,在某些业务场景,用isNotBlank 比 isNotEmpty要好
try {
JsonElement parse = new JsonParser().parse(extra);
if (parse.isJsonObject() || parse.isJsonArray()) {
//YES
}
} catch (JsonSyntaxException e) {
//ignore
}
// NO
// 对象deep copy
MyUser myUser = new MyUser();
myUser.setSkuId(1L);
Gson gson = new Gson();
MyUser newUser = gson.fromJson(gson.toJson(myUser), MyUser.class);
System.out.println(newUser);
myUser.setSkuId(77777777777L);
System.out.println(newUser);
// 集合deep copy
List<MyUser> newList = JSON.parseArray(JSON.toJSONString(list), MyUser.class);//fastjson
System.out.println(newList);
u1.setSkuId(777777777777777L);
System.out.println(newList);
用于数字的转字符串展示
1、s1 + s2 + s3会被自动优化为sb.append(s1).append(s2).append(s3).toString()
由于字符串的不可变性,连接 n 个字符串重复使用字符串连接操作,需要 n2 的时间。
sb 对象内部维护一个字符数组。操作都是在字符数组上进行,append 方法的时间是线性的
2、字符串不适合替代其他值类型,数据本质上确实是文本信息时,使用字符串才合理
3、参考:唯品会的工具类StringBuilder在高性能场景下的引用
https://github.com/vipshop/vjtools/blob/master/vjkit/src/main/java/com/vip/vjtools/vjkit/text/StringBuilderHolder.java
将json格式的内容存储mysql,mysql中字段为json而非Varchar