Module id.xfunction
Package id.xfunction

Class XJson

Object
XJson

public class XJson extends Object
Set of functions to work with JSON format.
  • Constructor Details

    • XJson

      public XJson()
  • Method Details

    • asString

      public static String asString(Object... pairs)
      Build a JSON from a given pair of objects (k1, v1, k2, v2, ...). String for each object is obtained by calling toString on the object itself.

      Example:

      
       XJson.asString(
           "k1", 123,
           "k2", "ggg",
           "k3", List.of("sg", "dfg", "dsfg")));
       

      Produces a string like: { "k1": "123", "k2": "ggg", "k3": ["sg", "dfg", "dsfg"] }

    • formatNumber

      public static String formatNumber(Number n)
      Format number to valid JSON representation.
      • disables grouping, example: 1,234.23 will be converted to 1234.23
      • disables scientific notation
      • converts "-0" to 0 if isNegativeZeroDisabled
      • limits fraction part to MAX_FRACTION_LEN
    • setLimitDecimalPlaces

      public static void setLimitDecimalPlaces(int n)
      Round all numbers in output JSON to N decimal places. By default it is equal to -1 so numbers are not rounded and included into JSON as is.
    • setNegativeZero

      public static void setNegativeZero(boolean isEnabled)
      Java allows negative zero. With this method you may disable it in the final JSON so that it will be replaced with positive zero instead.
    • asString

      public static <V> String asString(Map<?,?> m)
      Build a JSON from a given pair of objects (k1, v1, k2, v2, ...). String for each object is obtained by calling toString on the object itself.

      All pairs will be processed in lexicographical order of their keys.

    • merge

      public static String merge(String... jsons)
      Merges multiple JSONs into one.

      Useful when you override toString on a subclass which returns JSON. In that case you can use this method to merge it with JSON produced from its super class.

      Example:

      
       return XJson.merge(
           super.toString(),
           XJson.asString(
               "k1", "v1",
               "k2", "v2"));