GsonUtils and strings

Article directory

      • 1. GsonUtils
      • 2. String itself can add log information
      • 3. Json and Map conversion
      • 4. Convert Date to Json string
      • 5. Json and List conversion
      • 6. Compare the differences between two JSON strings
      • 7. String filling: Filling in when generating document number
      • 8. Use of String.format()
      • 9. Truncate string
      • 10.split
      • The difference between isNotBlank and isNotEmpty
      • 11. Determine whether the string is in Json string format
      • 12. deep copy
      • Supplement: About msyql’s Json format

1. GsonUtils

  • Json string to object
  • Object to Json string
@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("Serialization failed", e);
        }
        return StringUtils.EMPTY;
    }
}
  • Tool usage
String str = "{"status":{"code":0,"__isset_bit_vector":[1]},"poiId":1}";
 TResponse tResponseA = GsonUtils.fromJson(str, TResponse.class);

2. String itself can add log information

String.format("Duplicate asyncCreateTask request with requestId=%s, billNo=%s, finish it fast.", request.getRequestId(), request.getNo());

3. Json and Map conversion

map.put("0915", "1");
map.put("0916", "2");
String jsonStr = GsonUtils.toJsonStr(map);
Map<String,String> json2Map = GsonUtils.fromJson(jsonStr,new TypeToken<HashMap<String,String>>(){}.getType());

4. Convert Date to Json string

If there is a Date type attribute field in the class, you need to set the date format when creating gson.
    Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd")
        .create();
    System.out.println(gson.toJson(new Date()));

5. Json and List conversion

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());

6. Compare the differences between two JSON strings

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"}";

        // method one:
        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 out of 2, 2 out of 1
        System.out.println(result.isMissingOnField());
        List<FieldComparisonFailure> fieldMissing = result.getFieldMissing();
        for (FieldComparisonFailure fieldComparisonFailure : fieldMissing) {<!-- -->
            System.out.println(fieldComparisonFailure.getExpected());//address
        }

        // 1 out of 2, not 1 out of 2
        System.out.println(result.isUnexpectedOnField());
        List<FieldComparisonFailure> fieldUnexpected = result.getFieldUnexpected();
        for (FieldComparisonFailure fieldComparisonFailure : fieldUnexpected) {<!-- -->
            System.out.println(fieldComparisonFailure.getActual());//author
        }

        //There are both in 1 and 2, but the val value is different
        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
        }


        //Method 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 out of 2, 2 out of 1
            if (v2 == null) {<!-- -->
                diffMap.put(k1, v1);
                continue;
            }

            // Both 1 and 2 are present, but they are different
            if (!Objects.equals(v1, v2)){<!-- -->
                diffMap.put(k1, "expect:" + v1 + ", actual:" + v2);
            }
        }
        json2Map.forEach((k2, v2) -> {<!-- -->
            Object v1 = json1Map.get(k2);
            // 1 out of 2, not 1 out of 2
            if (v1 == null) {<!-- -->
                diffMap.put(k2, v2);
            }
        });

        System.out.println(diffMap);//{temp=expect:2.0, actual:3.0, address=bj, author=mjp}
    }

7. String filling: filling when generating the document number

Long billType = 1L;
System.out.println("a" + StringUtils.leftPad(billType + "", 5, "0"));// a00001
That is, add 0 to the left side of billType until 00001 forms 5 digits.
The right padding and both side padding APIs are as follows:
public static String leftPad(final String str, final int size, String padStr)
 public static String center(String str, final int size, String padStr)

8. Use of String.format()

Reference: https://blog.csdn.net/lonely_fireworks/article/details/7962171

  • Simple to use
int time = 3;
String nameParis = String.format("The maximum number of times reached %s times", time);
  • Complex use
String contentFormat = "The [%s] items you sold today are likely to be sold out, and the estimated sales loss is pcs [%s] pieces, and the estimated sales loss is [%s" + "] yuan, If you need to contact us for replenishment, please click "[Prompt Processing|%s]" to view details.";

String url = "sell.out.warning.link:https://xxx.xxx.xxx" + ".com?warnType=%s & amp;categoryId=%s"

String result = String.format(contentFormat, skuCount, salePcs.stripTrailingZeros().toPlainString(),
                saleGmv.stripTrailingZeros().toPlainString(),
                String.format(url, warnType, categoryId));

1. Fill warnTpe and categoryId into the url to become a complete connection url.

2. The sku number, pcs, GMV, and the four-digit value of the link url are processed in time and filled into %s of the contentFormat.

9. Truncate string

String s = "Hello to everyone is really good";
String truncate = StringUtils.truncate(s, 2, 4);
System.out.println(truncate);//Good is true

10, split

https://www.runoob.com/java/java-string-split.html

The difference between isNotBlank and isNotEmpty

public static boolean isNotEmpty(String str): Determine whether a string is not empty. Space characters cannot be excluded here, that is, StringUtils.isNotEmpty(" ") = true
  Here is an example:
StringUtils.isNotEmpty(null) = false
StringUtils.isNotEmpty("") = false
StringUtils.isNotEmpty(" ") = true

  
public static boolean isNotBlank(String str)
Determine whether a string is not empty, has a length that is not 0, and does not consist of whitespace characters, that is, StringUtils.isNotBlank(" ") = false
 Here is an example:
StringUtils.isNotBlank(null) = false
StringUtils.isNotBlank("") = false
StringUtils.isNotBlank(" ") = false
 
Therefore, in some business scenarios, it is better to use isNotBlank than isNotEmpty.

11. Determine whether the string is in Json string format

try {<!-- -->
     JsonElement parse = new JsonParser().parse(extra);
      if (parse.isJsonObject() || parse.isJsonArray()) {<!-- -->
                //YES
       }
} catch (JsonSyntaxException e) {<!-- -->
            //ignore
}
// NO

12. deep copy

 // Object 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);

        // Collection deep copy
        List<MyUser> newList = JSON.parseArray(JSON.toJSONString(list), MyUser.class);//fastjson
        System.out.println(newList);
        u1.setSkuId(777777777777777L);
        System.out.println(newList);

Supplement: About msyql’s Json format

Store the content in json format in mysql. The fields in mysql are json instead of Varchar.

  • It is recommended to use field name json directly after 5.7
  • Generally, varchar(n) is used. Note: n should not be too large. If it is too large, consider JSON.