Class Json

java.lang.Object
com.codename1.backend.Json

public final class Json extends Object

JSON for server-side binaries: the core's strict reader and a streaming writer.

Reading is com.codename1.io.JSONParser#parseStrict, the same code the device runs (JSONParser is shared with the backend). This class once carried a parser of its own because JSONParser reached com.codename1.processing.Result and, through it, the XML DOM; that dependency is gone. Writing stays here because it streams into a ByteSink and honours Writable and Encoder, which the core writer has no notion of.

Values map as: object to LinkedHashMap (insertion-ordered so a round trip is stable), array to ArrayList, string to String, number to Double or Long, true/false to Boolean, null to null. Anything malformed -- trailing content, a raw control character in a string, a number outside the JSON grammar or a long, nesting deeper than 512 -- throws IOException.

  • Method Details

    • parseObject

      public static Map parseObject(String json) throws IOException
      Parses a JSON object. Throws IOException on anything malformed.
      Throws:
      IOException
    • parse

      public static Object parse(String json) throws IOException
      Parses any JSON value. Throws IOException on anything malformed.
      Throws:
      IOException
    • write

      public static String write(Object value)
    • write

      public static void write(Object value, ByteSink out)

      Writes JSON as UTF-8 bytes straight into a reusable buffer.

      The String-returning form above builds a StringBuilder, grows its char[] several times, copies it into a String and then encodes that to bytes -- four allocations for a document the server is about to write to a socket and discard. Measured on a small JSON response, that chain was most of the per-request allocation once the response head had been dealt with, and it kept the collector's run-ahead cap firing.

      Same output as write(Object), byte for byte.

    • writeString

      public static void writeString(String value, ByteSink out)

      One JSON string, escaped, straight into out.

      Public because generated code calls it. A codec that knows its field types at build time emits a direct call here instead of putting the value in a Map and letting write(Object) rediscover its type at run time.

    • writeValue

      public static void writeValue(Object value, ByteSink out)
      One JSON value of unknown type, for the cases a generated codec cannot resolve statically (an unmodelled java.* type, a heterogeneous collection). The generated code uses the typed calls wherever it can and falls back here only where it must.