javajsonparsinggson

how to parse "key": 1b as byte using Gson?


I'm using Gson to parse a JSON string like this:

{
  "key": 1b
}

However, when I parse this using JsonParser.parseString(), the value 1b is interpreted as the string "1b" instead of being parsed as a byte.

Here is the code I'm using:

JsonElement element = JsonParser.parseString(json);
System.out.println(element.getAsJsonObject().get("key")); // Outputs: "1b"

My expectation was that 1b would be parsed as a byte, similar to how 1 is parsed as a number. Is there a way to make Gson recognize 1b as a byte literal?

If not, what's the recommended way to parse such pseudo-JSON values that use Java-style type suffixes like b, s, l, etc.?

Thanks in advance!


Solution

  • The issue is not with Gson. JSON simply does not support numeric suffixes. In the JSON specifications (RFC 8259),

       Numeric values that cannot be represented in the grammar below (such
       as Infinity and NaN) are not permitted.
    
          number = [ minus ] int [ frac ] [ exp ]
    
          decimal-point = %x2E       ; .
    
          digit1-9 = %x31-39         ; 1-9
    
          e = %x65 / %x45            ; e E
    
          exp = e [ minus / plus ] 1*DIGIT
    
          frac = decimal-point 1*DIGIT
    

    Hence, Gson tries to interpret your data as a string. Since suffixes such as b, s, and l are not a JavaScript feature, you'll need to treat them as a string and parse it later.